The -match and -notmatch operators return true or false when testing strings:
'The cow jumped over the moon' -match 'cow' # Returns true 'The cow' -match 'The +cow' # Returns true
In the preceding example, the + symbol is reserved; it indicates that The is followed by one or more spaces before cow.
Like the other comparison operators, if match is used against an array, it returns each matching element instead of true or false. The following comparison will return the values one and three:
"one", "two", "three" -match 'e'
In addition to returning a true or false value about the state of the match, a successful match will add values to a reserved variable, $matches. For example, the following regular expression uses a character class to indicate it should match any character from 0 to 4 repeated 0 or more times:
'1234567689' -match '[0-4]*'
Once the match has been executed, the matches variable (a hashtable) will be populated with the part of the string that matched the expression:
PS> $matches
Name Value
---- -----
0 1234
Regular expressions use parentheses to denote groups. Groups may be used to capture interesting elements of a string:
PS> 'Group one, Group two' -match 'Group (.*), Group (.*)'
True
PS> $matches
Name Value
---- -----
2 two
1 one
0 Group one, Group two
In the preceding example, the match operator is run first then the matches variable is displayed. The captured value one is held in the first group, and is accessible using either of the following statements:
$matches[1] $matches.1