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
Quoting is when you use the exact words from a source. You will need to put quotation marks around the words that are not your own and cite where they came from.
A direct quotation is a report of the exact words of an author or speaker and is placed inside quotation marks in a written work. For example, Dr. King said, "I have a dream."
Quoting is an important technique used to include information from outside sources in academic writing. When using quotations, it is important that you also cite the original reference that you have taken the quotation from, as your citations provide your reader with a map of the research that you have done.
To cite a direct quote in APA, you must include the author's last name, the year, and a page number, all separated by commas. If the quote appears on a single page, use “p.”; if it spans a page range, use “pp.” An APA in-text citation can be parenthetical or narrative.
In your second line:
'abc' -replace 'a(\w)', "$1"
Powershell replaces the $1 before it gets to the regex replace operation, as others have stated. You can avoid that replacement by using a backtick, as in:
'abc' -replace 'a(\w)', "`$1"
Thus, if you had a string in a variable $prefix which you wanted to include in the replacement string, you could use it in the double quotes like this:
'abc' -replace 'a(\w)', "$prefix`$1"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With