Named capture groups

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 previous simple example as follows:

PS> 'first second third' -match '(?<One>first) (?<Two>second) (?<Three>third)'
True

PS> $matches

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 this approach is that the output is not ordered, as it has been created from a hash table.

..................Content has been hidden....................

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