Search notes:

PowerShell: -Match and -Notmatch regular expression matching operators

-match and -nomatch are PowerShell comparison operators that compare a string value against a regular expression.
-match returns true if the tested string matches the given regular expression. -notmatch returns true if the tested string does not match the given regular expression.
By default, -match and -nomatch treat strings case-insensitvely (as is the case for all, or most(?) string operations in PowerShell).
In order to use case-sensitive regular expressions, -cmatch or -cnomatch must be used. It is possible to explicitly state an insensitive match with -imatch and -inomatch.

Capture matched portions in the $matches variable

The matched portions of the tested string are captured in the $matches (array) variable.
The first element of this array stores the entire match, the subsequent elements the individual parts that were captured with parentheses:
'First number: 42, second number: 99, third number 18.' -match '(\d+)\D+(\d+)\D+(\d+)'
#
#  True

#  Print entire matching string:
$matches[0]
#
#  42, second number: 99, third number 18

#  First, second and third number:
$matches[1]
#
#  42

$matches[2]
#
#  99

$matches[3]
#
#  18
Github repository about-PowerShell, path: /language/operator/comparison/match_notmatch/matches-variable.ps1
For easier reading, it's also possible to capture a matched portion of the text with name-tag. This requires the capturing parenthesis to look look like so: (?<NAME>REGEXP). NAME then becomes the key in the $matches hash table:
'First number: 42, second number: 99, third number 18.' -match '(?<first>\d+)\D+(?<second>\d+)\D+(?<third>\d+)'
#
#  True

#  Print entire matching string:
$matches[0]
#
#  42, second number: 99, third number 18

#  First, second and third number:
$matches['first']
#
#  42

$matches['second']
#
#  99

$matches['third']
#
#  18
Github repository about-PowerShell, path: /language/operator/comparison/match_notmatch/named-capture-group.ps1

Misc

-match is the only operator that is not allowed in DATA sections.

See also

The -replace operator also uses regular expressions.
Comparison operators

Index