This question already has answers here:
How to handle backslash character in PowerShell -replace string operations?
(2 answers)
Closed 6 years ago.
Folks
I am unable to replace the below string in PowerShell, initially I suspected it to be due to regexp and used [regex]::Escape() to resolve the \ to double slash however it still does not work. Can you please suggest?
PS C:\User>"C:clog" -replace "C:c" , ""
PS C:\User>log
PS C:\User>"C:\\c\\log" -replace "C:\\c\\", ""
PS C:\User>C:\\c\\log
Use Split-Path, it is designed for this:
Split-Path "C:\\c\\log" -Leaf
# returns "log"
Related
This question already has answers here:
Use a function in Powershell replace
(3 answers)
Powershell - How to UpperCase a string found with a Regex [duplicate]
(1 answer)
Lambda Expression in Powershell
(3 answers)
Closed 2 years ago.
The community reviewed whether to reopen this question 1 year ago and left it closed:
Original close reason(s) were not resolved
Was trying to simplify some PowerShell string replacement code, and came across something I can't quite explain. To be clear, I know how to find a substring and replace it/transform it with another value. What I'm asking for here is an explanation of this behavior and why it doesn't work this way.
With a regular string, whether it's a variable or hard-coded, I can modify the string how I see fit after it has been rendered. For example:
($greeting = 'HELLO'.ToLower()) # ===> hello
This produces the expected output by returning a lowercase copy of the string. However, I tried this using the -replace operator and was met with an interesting result:
$greeting -replace '\w+', '$0'.ToUpper() # ===> hello
I was expecting the matched pattern in the string to be replaced with an uppercase copy of the match, but this isn't happening. I tried a few other increasingly ugly methods to see if there was some way to get this to work but to no avail:
$greeting -replace '\w+', ('$0').ToUpper() # ===> hello
$greeting -replace '\w+', "$(('$0').ToUpper())" # ===> hello
$greeting -replace '\w+', "`$0".ToUpper() # === hello
$greeting -replace '\w+', '`$0'.ToString().ToUpper() # ===> hello
$greeting -replace '\w+', (('$0').ToString()).ToUpper() # ===> hello
I also tried -creplace in place of -replace for a few of these but that also didn't have any effect. Why am I unable to transform the result of a match when using PowerShell's -replace operator?
I tested this with both PowerShell 5.1 and 7 so this behavior extends between MS PowerShell and PowerShell Core.
ToUpper() is executed before the resulting upper-case string is passed to -replace as the substitute argument - and the upper-case version of $0 is just $0, so no different from omitting .ToUpper() entirely.
If you want ToUpper() called as part of the substitution routine you have to pass a scriptblock as the substitute argument:
$greeting -replace '\w+', {$_.Value.ToUpper()}
This only works in PowerShell 6.2 and up, in Windows PowerShell you have to call [regex]::Replace() directly:
[regex]::Replace($greeting, '\w+', {param($m) $m.Value.ToUpper()})
This question already has an answer here:
powershell: how to escape all regex characters from a string
(1 answer)
Closed 4 years ago.
I need to replace ^~^ with a tab (\t) in a CSV file in PowerShell.
I tried escaping caret with a backtick (`^~`^) but it doesn't work. How do I do this?
$file=Import-Csv $dataFilePath
$file -replace "\`^~\`^", "\`t"
Is that what you're looking for?
>$s = "^~^"
>$s -replace "\^\~\^", "``t"
`t
Hope that helps.
This question already has answers here:
Is there a way to make Perl regex searches case-insensitive?
(2 answers)
Closed 4 years ago.
Is there a minimal adjustment that i can do to the below code to cover cases where the ManagedElement String is of any case?
if($cmd =~ /^ManagedElement/){
$cmd = "TreeNavigation";
}
Yes, put an i at the end.
if($cmd =~ /^ManagedElement/i){
$cmd = "TreeNavigation";
}
Here is the documentation for future reference.
This question already has answers here:
Quoting -replace & variables
(5 answers)
Closed 4 years ago.
I am trying to replace filenames in a given folder, but using regular expressions as a filter and in the new filenames, in PowerShell.
For example, a file name "CEX-13" should be renamed to "C-0013"; "CEX-14" should change to "C-0014", etc.
I have this, but I get an error that I cannot create a file that already exists.
My current code is:
foreach ($file in get-childitem | where-object {$_.name -match "^CEX-(\d\d)"})
{
rename-item $file -newname ($file.name -replace "^CEX-(\d\d)", "C-00$1")
}
Any help will be greatly appreciated.
You need the dollar in the replacement to get past the PowerShell variable expansion in strings, and stay as a dollar sign as it gets to the regex engine.
Currently "C-00$1" becomes "C-00" and all the files will get the same name.
You need to escape it with a backtick
"C-00`$1"
or use single quotes 'C-00$1'
This question already has answers here:
Regular expression matching in PowerShell
(5 answers)
Closed 6 years ago.
Given a string:
$assemblyVersion = '[assembly: AssemblyFileVersion("8.0.0.866")]'
I have a regex that will find the assembly numbers:
(\d+\.)(\d+\.)(\d+\.)(\*|\d+)
These lines confirms it has found a match:
$extractedVersion = $assemblyVersion -match "(\d+\.)(\d+\.)(\d+\.)(\*|\d+)";
How do you then extract the match from the original string $assemblyVersion?
Reading this article i don't quite get how you do it...
I tried:
$assemblyVersion
$extractedVersion = $assemblyVersion -match "?<assembly>(\d+\.)(\d+\.)(\d+\.)(\*|\d+)";
Write-Host "Extracted " $extractedVersion["assembly"]
Doesn't work.
My regex may not be optimal either.
This stackoverflow answer doesn't help
I got it:
$assemblyVersion = '[assembly: AssemblyFileVersion("8.0.0.866")]'
$assemblyVersion -match "(\d+\.)(\d+\.)(\d+\.)(\*|\d+)";
Write-Host "Extracted " $matches[0]