Alternation

The alternation (or) character in a regular expression is a pipe (|). This is used to combine several possible regular expressions. A simple example is to match a list of words:

'one', 'two', 'three' | Where-Object { $_ -match 'one|three' } 

The alternation character has the lowest precedence; in the previous expression, every value is first tested against the expression to the left of the pipe and then against the expression to the right of the pipe.

The goal of the following expression is to extract strings that only contain the words one or three. Adding the start and the end of string anchors ensures that there is a boundary. However, because the left and right are treated as separate expressions, the result might not be as expected when using the following expression:

PS> 'one', 'one hundred', 'three', 'eighty three' |
Where-Object { $_ -match '^one|three$' }
one
one hundred
three
eighty three

The two expressions are evaluated as follows:

  • Look for all strings that start with one
  • Look for all strings that end with three

There are at least two possible solutions to this problem. The first is to add the start and end of string characters to both expressions:

'one', 'one hundred', 'three', 'eighty three' | 
Where-Object { $_ -match '^one$|^three$' } 

Another possible solution is to use a group:

'one', 'one hundred', 'three', 'eighty three' | 
Where-Object { $_ -match '^(one|three)$' } 

Grouping is discussed in detail in the following section.

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

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