引用 -replace &变量 [英] Quoting -replace & variables

查看:65
本文介绍了引用 -replace &变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是对我之前的问题的回答:

This is in response to my previous question:

PowerShell:-replace、regex 和 ($) 美元符号问题

我的问题是:为什么这两行代码有不同的输出:

My question is: why do these 2 lines of code have different output:

'abc' -replace 'a(\w)', '$1'
'abc' -replace 'a(\w)', "$1"

AND 根据下面的 2 篇文章,为什么单引号中的变量 '$1' 不用作文字字符串?单引号中的所有内容都应视为文字文本字符串,对吗?

AND according to the 2 articles below, why doesn't the variable '$1' in single quotes get used as a literal string? Everything in single quotes should be treated as a literal text string, right?

http://www.computerperformance.co.uk/powershell/powershell_quotes.htm
http:///blogs.msdn.com/b/powershell/archive/2006/07/15/variable-expansion-in-strings-and-herestrings.aspx

推荐答案

当您使用单引号时,您告诉 PowerShell 使用字符串字面量,这意味着开始和结束引号之间的所有内容都将按字面意思解释.

When you use single quotes you tell PowerShell to use a string literal meaning everything between the opening and closing quote is to be interpreted literally.

当您使用双引号时,PowerShell 将解释双引号内的特定字符.

When you use double quotes, PowerShell will interpret specific characters inside the double quotes.

请参阅get-help about_quoting_rules 或点击此处.

美元符号在正则表达式和 PowerShell 中具有特殊含义.如果您打算将美元符号用作正则表达式,则需要使用单引号.

The dollar sign has a special meaning in regular expressions and in PowerShell. You want to use the single quotes if you intend the dollar sign to be used as the regular expression.

在您的示例中,正则表达式 a(\w) 匹配字母a",然后是在反向引用 #1 中捕获的单词字符.因此,当您使用 $1 替换时,您将使用反向引用匹配 b 替换匹配的文本 ab.所以你得到 bc.

In your example the regex a(\w) is matching the letter 'a' and then a word character captured in back reference #1. So when you replace with $1 you are replacing the matched text ab with back reference match b. So you get bc.

在使用双引号的第二个示例中,PowerShell 将 "$1" 解释为内部包含变量 $1 的字符串.您没有名为 $1 的变量,因此它为空.所以正则表达式将 ab 替换为 null,这就是为什么你只能得到 c.

In your second example with using double quotes PowerShell interprets "$1" as a string with the variable $1 inside. You don't have a variable named $1 so it's null. So the regex replaced ab with null which is why you only get c.

这篇关于引用 -replace &变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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