A common task for regex is to replace text that matches a pattern with a new value.
#Sample text
$text = @"
This is (a) sample
text, this is
a (sample text)
"@
#Sample pattern: Text wrapped in ()
$pattern = '\(.*?\)'
#Replace matches with:
$newvalue = 'test'
The -replace
operator in PowerShell can be used to replace text matching a pattern with a new value using the syntax 'input' -replace 'pattern', 'newvalue'
.
> $text -replace $pattern, $newvalue
This is test sample
text, this is
a test
Replacing matches can also be done using the Replace()
method in the [RegEx]
.NET class.
[regex]::Replace($text, $pattern, 'test')
This is test sample
text, this is
a test