Restricting alternation

Alternation is the lowest precedence operator. In a sense, it might be wise to consider it as describing an ordered list of regular expressions to test.

Placing an alternation statement in parentheses reduces the scope of the expression.

For example, it is possible to match a multi-line string using alternation:

PS> $string = @'
First line
second line
third line
'@

PS> if ($string -match 'First(.| ? )*line') { $matches[0] }
First line
second line
third line

In this example, as . does not match the end of line character, using alternation allows each character to be tested against a broader set. In this case, each character is tested to see if it is any character, or .

A regular expression might be created to look for files with specific words or parts of words in the name:

Get-ChildItem -Recurse -File |  
    Where-Object { $_.Name -match '(pwd|pass(word|wd)?).*.(txt|doc)$' } 

The expression that compares filenames looks for strings that contain pwd, pass, password, or passwd followed by anything with the extension .txt or doc.

This expression will match any of the following (and more):

pwd.txt 
server passwords.doc 
passwd.txt 
my pass.doc 
private password list.txt 
..................Content has been hidden....................

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