This is in response to my previous question:
PowerShell: -replace, regex and ($) dollar sign woes
My question is: why do these 2 lines of code have different output:
'abc' -replace 'a(\w)', '$1'
'abc' -replace 'a(\w)', "$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
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.
When you use double quotes, PowerShell will interpret specific characters inside the double quotes.
See
get-help about_quoting_rulesor click here.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.
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$1you are replacing the matched textabwith back reference matchb. So you getbc.In your second example with using double quotes PowerShell interprets
"$1"as a string with the variable$1inside. You don’t have a variable named$1so it’s null. So the regex replacedabwith null which is why you only getc.