Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular expression invalid when replacing in powershell

$100 = "$env:APPDATA/somthing"
$iamhere = "C:/example"
$100 = $100 -replace "`$env:APPDATA\somthing", "$iamhere" 

I want $100 replaced by $iamhere of its contents (in text form) although I get this error.

Regular expression pattern is not valid: $env:APPDATA\somthing.
At line:1 char:1
$100 = $100 -replace "`$env:APPDATA\somthing", "$iamhere"
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
   + CategoryInfo          : InvalidOperation: ($env:APPDATA\somthing:String) [], RuntimeException
   + FullyQualifiedErrorId : InvalidRegularExpression

I think this is because I am trying to replace some text with a directory, but I want the text inside the variable of $iamhere

like image 612
Collin Avatar asked Sep 24 '13 22:09

Collin


2 Answers

The -replace operator will parse the input string you provide as a regular expression. The \ character is a special character in regular expressions and so if you want it to be treated literally, you need to escape it by adding a \ in front of it. Fortunately .NET provides a handy function for doing that for you:

# ~> [Regex]::Escape("$env:APPDATA/somthing")
C:\\Users\\username\\AppData\\Roaming/somthing

So just update your example like this:

$100 = $100 -replace [Regex]::Escape("$env:APPDATA/somthing"), $iamhere

Note that you don't need the quotes around $iamhere (but since it's a string, it doesn't make a difference).

like image 169
zdan Avatar answered Sep 30 '22 15:09

zdan


you could use *.replace instead

$100 = "$env:APPDATA/somthing"

$iamhere = "C:/example"

$100 = $100.replace("$env:APPDATA/somthing", "$iamhere")

it won't use regex then

like image 34
JohnW Avatar answered Sep 30 '22 14:09

JohnW