Regular Replacements
As I mentioned before, Tobias at PowerShell.com has written a follow-up of his primer on using PowerShell regular expression, focusing on using regular expressions to slice and dice text. He has added a third installment to the series that looks at using Regular Expressions to perform string replacements.
In Part 1, you lerned how Regular Expressions can extract useful information from noise text. In Part 2, we looked at using Regular Expressions to split text, yet another powerful technique to extract the pieces of information you may need. Today, we conclude our little excurse and use Regular Expressions to replace text. Fasten your seat belts, please!
Replacing Old Text With New Stuff
Replacing some information inside a text with some other information seems to be pretty straight-forward: simply use -replace and tell the operator which text you would like to replace with other text:
PS> ‘Hello World!’ -replace ‘World’, ‘PowerShell’
Hello PowerShell!It is not obvious at first that -replace in reality takes a Regular Expression. You may notice accidentally when you try and use characters that have a special meaning, like here:
PS> ‘Hello.’ -replace ‘.’, ‘!’
!!!!!!Huh? Well, “.” is a special RegEx placeholder and represents any character, so the result is right. If you must use special characters, they need to be escaped:
PS> ‘Hello.’ -replace ‘.’, ‘!’
Hello!Remember the trick from our previous parts? If you aren’t sure which characters need to be escaped, ask PowerShell!
PS> [RegEx]::Escape(‘Hello.’)
Hello.
5 months ago - link

