PowerShell RegEx
'the goose' -match 'g[oe]{2}se' # true
Escaping
'f\d.' -match [regex]::escape('\d.')
Capture groups:
'the goose' -match 'g([oe]{2})s(e)'
$Matches[1]
The automatic variable $Matches
is a hashtable with the captured text. Key 0 holds the entire match.
> $Matches
Name Value
---- -----
2 e
1 oo
0 goose
Note that the hashtable contains only the first occurrence of any matching pattern. e.g. the goose geese
β goose
only (docs)
Named Captures: use ?<keyname>
, e.g. (?<keyname>pattern)
:
'some geese flew south' -match '(?<bird>g[oe]{2}se) fl(?<tense>ew|y) (?<dir>\w+)'
> $Matches
Name Value
---- -----
tense ew
bird geese
dir south
0 geese flew south
Find/Replace
> 'red fox, brown fox, white swan' -replace '\w+ fox','pooh bear'
pooh bear, pooh bear, white swan
$&
: all matched text
> 'quick fox, quack fox, a quick quack fox' -replace 'qu\w+','$& $&'
quick quick fox, quack quack fox, a quick quick quack quack fox
With captures:
> '1 red fox, 2 brown bears, 3 white swans' -replace
'(\d) (\w+) (?<animal>([^s\W]|s\w)+)s?',
'${animal} x$1 ($2)'
fox x1 (red), bear x2 (brown), swan x3 (white)
Special rules for using $
since itβs used in string expansion: docs
(summary)
Using
$
in general: use literal strings''
$
as a literal: use$$
β e.g.'5.99' -replace '(.+)','CAD$$$&'
βCAD$5.99
If not using literal strings, escape the $
, i.e. "`$1"
and "`$`$"
Another method: Select-String
Select-String
$m = 'the goose geese' | sls -pattern 'g([oe]{2})se'
$m.matches.groups[1]
> $m.matches
Groups : {0, 1}
Success : True
Name : 0
Captures : {0}
Index : 0
Length : 5
Value : goose
# capture groups
> $m.matches.groups[1]
Success : True
Name : 1
Captures : {1}
Index : 1
Length : 2
Value : oo
where sls
is an alias for Select-String