Contents
Replacement Operator
PowerShell provides several options to help you replace text in a string with other text. The -replace operator replaces all or part of a value with the specified value using regular expressions. It replaces every occurrence of the exact string you specify with the exact replacement string that you provide. The -replace
operator provides much more flexibility because its arguments are regular expressions that can match and replace complex patterns.
Operators | Description |
---|---|
-replace | replace a string pattern |
Syntax:
<input> <operator> <original> <substitute>
The syntax of the -replace operator is as follows, where the <original> placeholder represents the characters to be replaced, and the <substitute> placeholder represents the characters that going to replace.
Example:
PS C:\>
$stringMsg = "Hi Welcome to dotnet-helpers.com"
$stringMsg -replace 'Hi' , "You are"
OUTPUT
You are Welcome to dotnet-helpers.com
By default, the -replace operator is case-insensitive. To make it case sensitive, you need to introduce ‘c’ as prefix like -creplace. To make it explicitly case-insensitive, you need to prefix ‘it’ like -ireplace.
Example:
Here the output will be same text beacuse we maked a replace operator as case sensitive, so ‘HI’ does’t macth with the string.
PS C:\>
$stringMsg = "Hi Welcome to dotnet-helpers.com"
$stringMsg -creplace 'HI' , "You are"
OUTPUT
Hi Welcome to dotnet-helpers.com