Use the Replace() method on the string itself to perform simple
replacements:
PS > "Hello World".Replace("World", "PowerShell")
Hello PowerShell
Use PowerShell’s regular expression -replace operator to perform more
advanced regular expression replacements:
PS > "Hello World" -replace '(.*) (.*)','$2 $1'
World Hello
Another, less common pitfall is wanting to use characters that have
special meaning to regular expressions as part of your replacement text. For example:
PS > "Power[Shell]" -replace "[Shell]","ful"
Powfulr[fulfulfulfulful]
That’s clearly not what we intended. In regular expressions,
square brackets around a set of characters means
“match any of the characters inside of the square brackets.”
In our example, this translates to “Replace the characters S, h, e, and l with ‘ful’.”
To avoid this, we can use the regular expression escape character to escape
the square brackets:
PS > "Power[Shell]" -replace "[Shell]","ful"
Powerful
However, this means knowing all of the regular expression special
characters and modifying the input string.
Sometimes we don’t control the input string,
so the [Regex]::Escape() method comes in handy:
PS > "Power[Shell]" -replace ([Regex]::Escape("[Shell]")),"ful"
Powerful
For extremely advanced regular expression replacement needs,
you can use a script block to accomplish your replacement tasks,
as described in Recipe 31.6. For example, to capitalize the first
character (w) after a word boundary ():
PS > "hello world" -replace '(w)',{ $_.Value.ToUpper() }
Hello World