Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Quoting -replace & variables

Tags:

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

like image 939
Vippy Avatar asked Feb 23 '12 22:02

Vippy


People also ask

What is quoting in writing?

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.

What is an example of quoting?

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."

What is quoting used for?

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.

How do you cite a quote?

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.


1 Answers

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"

like image 77
David Rogers Avatar answered Oct 19 '22 13:10

David Rogers