Capture groups can be given names. The name must be unique within the regular expression.
The following syntax is used to name a group:
(?<GroupName>Expression)
This may be applied to the simple previous example:
PS> 'first second third' -match '(?<One>first) (?<Two>second) (?<Three>third)'; $matches
True
Name Value
---- -----
One first
Three third
Two second
0 first second third
In PowerShell, this adds a pleasant additional capability. If the goal is to tear apart text and turn it into an object, one approach is as follows:
if ('first second third' -match '(first) (second) (third)') { [PSCustomObject]@{ One = $matches[1] Two = $matches[2] Three = $matches[3] } }
This produces an object that contains the result of each (unnamed) match group in a named property.
An alternative is to use named matches and create an object from the matches hash table. When using this approach, $matches[0] should be removed:
PS> if ('first second third' -match '(?<One>first) (?<Two>second) (?<Three>third)') {
$matches.Remove(0)
[PSCustomObject]$matches
}
One Three Two
--- ----- ---
first third second
A possible disadvantage of the previous approach is that the output is not ordered as a hashtable.