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

^

'aba' -match '^a'

End of a string

$

'cbc' -match 'c$'

Word boundary



'Band and Land' -match 'and'

 

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 that is three or more directories deep from a given set:

$env:PATH -split ';' | Where-Object { $_ -match '\.+\.+\.+$' } 

The word boundary anchor 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 or a part of a word.

For example, if the intent is to -replace the word day in the following string, then attempting this without the word boundary replaces too much:

'The first day is Monday' -replace 'day', 'night' 
'Monday is the first day' -replace 'day', 'night' 

Adding the word boundary avoids the problem without significantly increasing the complexity:

'The first day is Monday' -replace 'day', 'night' 
'Monday is the first day' -replace 'day', 'night' 
..................Content has been hidden....................

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