在powershell中替换时,正则表达式无效

Col*_*ter 3 powershell powershell-3.0

$ 100 ="$ env:APPDATA/somthing"

$ iamhere ="C:/ example"

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

我希望100美元替换为其内容的$ iamhere(以文本形式),虽然我收到此错误.

正则表达式模式无效:$ env:APPDATA\somthing.

在行:1个字符:1

$ 100 = $ 100 -replace"`$ env:APPDATA\somthing","$ iamhere"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~~

  • CategoryInfo:InvalidOperation:($ env:APPDATA\somthing:String)[],RuntimeException
  • FullyQualifiedErrorId:InvalidRegularExpression

我想这是因为我试图用目录替换一些文本,但我希望$ iamhere变量内的文本谢谢,CollinScripter

zda*_*dan 10

-replace运营商将解析您提供的正则表达式输入字符串.该\字符是在正则表达式特殊字符,所以如果你希望它是字面上处理,你需要通过添加一个逃脱它\在它的前面.幸运的是,.NET为您提供了一个方便的功能:

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

所以只需像这样更新你的例子:

$100 = $100 -replace [Regex]::Escape("$env:APPDATA/somthing"), $iamhere
Run Code Online (Sandbox Code Playgroud)

请注意,您不需要$ iamhere周围的引号(但因为它是一个字符串,所以没有区别).


小智 5

你可以使用*.replace,而不是

$100 = "$env:APPDATA/somthing"

$iamhere = "C:/example"

$100 = $100.replace("$env:APPDATA/somthing", "$iamhere")
Run Code Online (Sandbox Code Playgroud)

然后它不会使用正则表达式