将包含美元符号的字符串传递给 -Replace 变量 [英] Passing string included dollar signs to -Replace Variable

查看:47
本文介绍了将包含美元符号的字符串传递给 -Replace 变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 powershell 替换 .config 文件中的一个句子.

I am trying to replace a sentence in .config file using powershell.

${c:Web.config} = ${c:Web.config} -replace

'$BASE_PATH$\Test\bin`$Test_TYPE`$\WebTest.dll' , 'c:\program Files\example\webtest.dll'

'$BASE_PATH$\Test\bin`$Test_TYPE`$\WebTest.dll' , 'c:\program Files\example\webtest.dll'

每次我尝试运行上面的代码时,我都会得到

Everytime I try to run the above code I get

"无效的正则表达式模式:$BASE_PATH$\Test\bin\$Test_TYPE$\WebTest.dll"在 c:\tests\runtesting.ps1 -replace<<<<$BASE_PATH$\Test\bin\$Test_TYPE$\WebTest.dll

"Invalid regular expression pattern: $BASE_PATH$\Test\bin\$Test_TYPE$\WebTest.dll" at c:\tests\runtesting.ps1 -replace <<<< $BASE_PATH$\Test\bin\$Test_TYPE$\WebTest.dll

如果我不使用反引号,美元符号和一些文本就会消失.

If I don't use the backtick the dollar signs will disappear and some text.

如何将字符串中的美元符号传递给 -replace?

How would I pass dollar signs in a string to -replace?

推荐答案

这是关于如何转义正则表达式.每个特殊字符(与正则表达式相关的特殊字符)例如 $ 都应该用 \

This is about how to escape regexes. Every special character (special with regards to regular expressions) such as $ should be escaped with \

'$A$B()[].?etc' -replace '\$|\(|\)|\[|\]|\.|\?','x'
'$BASE_PATH$\Test\bin$Test_TYPE$\WebTest.dll' -replace '\$BASE_PATH\$\\Test\\bin\$Test_TYPE\$\\WebTest.dll','something'

当正则表达式如下时将使用反引号:

The backtick would be used when the regex would be like this:

'$A$B' -replace "\`$",'x'

这篇关于将包含美元符号的字符串传递给 -Replace 变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆