$matches contains a hashtable (Implicit)

The -match operator matches a pattern and returns a result.  However, along with the result, it also sets the $matches variable which contains the portions of the string that are matched by individual parts of the regular expressions.  $matches contains a hashtable where the keys of the hashtable are indexes that correspond to the parts of the pattern that is matched.  The values are the substrings of the target string that are matched.  Here is an example from the excellent Windows PowerShell in Action by Bruce Payette.

PS C:/> "abcdef" -match "(a) (((b)(c))de)f"
True
PS C:/> $matches
Key        Value
---        -----
5          c
4          b
3          bc
2          bcde
1          a
0          abcdef

You’ll noticed that there is one extra entry in the $matches hashtable beyond the 5 specified patterns.  This is because there is always a default element that represents the entire string that matched.

Since PowerShell is built on .NET regular expressions, you are not limited to index based keys as illustrated above.  This can be a pain when trying figure out which key index matches which matched pattern.  The .NET regular expression implementation allows for named captures by palcing the sequence “?” immediate inside the parenthesis that indicate the matching group.  The above example with named keys would look like this:

PS C:/> "abcdef" -match "(?a) (?((?b)(?c))de)f"
True
PS C:/> $matches
Key        Value
---        -----
o1         c
e3         b
e4         bc
o2         bcde
1          a
0          abcdef
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s