Anchors
An anchor does not match a character; instead, it matches what comes before (or after) a character:
Description | Character | Example |
Beginning of a string |
|
|
End of a string |
|
|
Word boundary |
|
|
Anchors are useful where a character, string, or word may appear elsewhere in a string and the position is critical.
For example, there might be a need to get values from the PATH
environment variable that starts with a specific drive letter. One approach to this problem is to use the start of a string anchor, in this case, retrieving everything that starts with the C
drive:
$env:PATH -split ';' | Where-Object { $_ -match '^C' }
Alternatively, there may be a need to get every path three or more directories deep from a set:
$env:PATH -split ';' | Where-Object { $_ -match '\\.+\\.+\\.+$' }
The word boundary matches both before and after a word. It allows a pattern to look for a specific word, rather than a string of characters that may be a word...