windows 如何在 Powershell 中转义反斜杠

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36748923/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 19:34:03  来源:igfitidea点击:

How to escape a backslash in Powershell

windowspowershell

提问by Zakaria Belghiti

I'm writing a powershell program to replace strings using

我正在编写一个 powershell 程序来使用

-replace "$in", "$out"

It doesn't work for strings containing a backslash, how can I do to escape it?

它不适用于包含反斜杠的字符串,我该如何转义它?

回答by briantist

The -replaceoperator uses regular expressions, which treat backslash as a special character. You can use double backslash to get a literal single backslash.

-replace运算符使用正则表达式,将反斜杠视为特殊字符。您可以使用双反斜杠来获得文字单反斜杠。

In your case, since you're using variables, I assume that you won't know the contents at design time. In this case, you should run it through [RegEx]::Escape():

在您的情况下,由于您使用的是变量,我假设您在设计时不会知道内容。在这种情况下,您应该运行它[RegEx]::Escape()

-replace [RegEx]::Escape($in), "$out"

That method escapes any characters that are special to regex with whatever is needed to make them a literal match (other special characters include .,$,^,(),[], and more.

该方法使用使它们成为文字匹配所需的任何内容来转义正则表达式特殊的任何字符(其他特殊字符包括., $, ^, (), [], 等等。

回答by Bacon Bits

You'll need to either escape the backslash in the pattern with another backslash or use the .Replace()method instead of the -replaceoperator (but be advised they may perform differently):

您需要使用另一个反斜杠对模式中的反斜杠进行转义,或者使用该.Replace()方法而不是-replace运算符(但请注意,它们的执行方式可能不同):

PS C:\> 'asdf' -replace 'as', 'b'
bdf
PS C:\> 'a\sdf' -replace 'a\s', 'b'
a\sdf
PS C:\> 'a\sdf' -replace 'a\s', 'b'
bdf
PS C:\> 'a\sdf' -replace ('a\s' -replace '\','\'), 'b'
bdf

Note that only the search pattern string needs to be escaped. The code -replace '\\','\\'says, "replace the escaped pattern string '\\', which is a single backslash, with the unescaped literal string '\\'which is two backslashes."

请注意,只有搜索模式字符串需要转义。代码-replace '\\','\\'说,“用两个反斜杠'\\'的未转义文字字符串替换转义的模式字符串,它是一个'\\'反斜杠。”

So, you should be able to use:

所以,你应该能够使用:

-replace ("$in" -replace '\','\'), "$out"

[Note: briantist's solutionis better.]

[注意:briantist的解决方案更好。]

However, if your pattern has consecutive backslashes, you'll need to test it.

但是,如果您的模式具有连续的反斜杠,则需要对其进行测试。

Or, you can use the .Replace()string method, but as I said above, it may not perfectly match the behavior of the -replaceoperator:

或者,您可以使用.Replace()string 方法,但正如我上面所说,它可能无法完全匹配-replace运算符的行为:

PS C:\> 'a\sdf'.replace('a\s', 'b')
a\sdf
PS C:\> 'a\sdf'.replace( 'a\s', 'b')
bdf