Search code examples
variablespowershellreplacequotes

Quoting -replace & variables


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


Solution

  • 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_rules or 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 $1 you are replacing the matched text ab with back reference match b. So you get bc.

    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.