Capturing values

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 (hash table) in the order that they appear in the expression. Consider the following example:

PS> 'first second third' -match '(first) (second) (third)'
True

PS> $matches

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))'
True

PS> $matches

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 4, 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.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.133.156.156