PS: String/Text Replacement

PS supports a built-in string search and replacement operator named –replace. The -replace operator uses a regular expression to search-and-replace through a string. The default behavior is it does a case insensitive similar to that of using –ireplace.  For a case sensitiveness, you need to use –creplace.

Default replace behavior:

PS C:> $str = "This is a SAMPLE string"
PS C:> write-host $Str
This is a SAMPLE string
PS C:> $str -replace "SAMple","Test"
This is a Test string
PS C:> write-host $Str
This is a SAMPLE string
PS C:>

Explicit case-insensitive replacement:

PS C:> write-host $Str
This is a SAMPLE string
PS C:>
$str -ireplace "SAMple","Test"
This is a Test string
PS C:>

Explicit case-sensitive replacement:

PS C:> write-host $Str
This is a SAMPLE string

PS C:> $str -creplace "SAMple","Test"
This is a SAMPLE string
PS C:> write-host $Str
This is a SAMPLE string
PS C:>
$str -creplace "SAMPLE","Test"
This is a Test string
PS C:>

Using matched strings with $<num> references:

PS C:> write-host $Str
This is a SAMPLE string

PS C:> $str -creplace "(This) (is)","$2 $1"
  a SAMPLE string
PS C:> $str -creplace "(This) (is)",’$2 $1′
is This a SAMPLE string
PS C:> $str -creplace "(This) (is)","`$2 `$1"
is This a SAMPLE string
PS C:>

Referring the matched string via $&:

PS C:> write-host $Str
This is a SAMPLE string

PS C:> $str -creplace "w",‘$& $&’
T Th hi is s i is s a a S SA AM MP PL LE E s st tr ri in ng g
PS C:> $str -creplace "(w+)",‘$& $&’
This This is is a a SAMPLE SAMPLE string string
PS C:>

Leave a Reply

Your email address will not be published. Required fields are marked *