The ability to capture values from a string is an incredibly useful feature of regular expressions.
When using the match operator, groups that have been captured are loaded into the matches variable (hashtable) in the order that they appear in the expression, for example:
PS> 'first second third' -match '(first) (second) (third)'; $matches
True
Name Value
---- -----
3 third
2 second
1 first
0 first second third
The first key, 0, is always the string that matched the entire expression. Numbered keys are added to the hash table for each of the groups in the order that they appear. This applies to nested groups as well, counting from the leftmost (:
PS> 'first second third' -match '(first) ((second) (third))'; $matches
True
Name Value
---- -----
4 third
3 second
2 second third
1 first
0 first second third
When using the replace operator, the matches variable is not filled, but the contents of individual groups are available as tokens for use in Replace-With:
PS>'first second third' -replace '(first) ((second) (third))', '$1, $4, $2'
first, third, second third
Use single quotes when tokens are included:
As was mentioned in Chapter 5, Operators, single quotes should be used when using capture groups in Replace-With. Tokens in double quotes will expand as if they were PowerShell variables.
As was mentioned in Chapter 5, Operators, single quotes should be used when using capture groups in Replace-With. Tokens in double quotes will expand as if they were PowerShell variables.