Powershell – Regular Expression

Regular expressions (regex or regexp) are extremely useful for 
 powerful search pattern language and also used in extracting information. Powershell makes use of Regular expression in several ways. 

Select-String

The above code search all the files inside the folder POC and scans for the lines that has a word “Error“.  The pattern parameter is a regular expression and in this case, the word Error is valid regex.

Following is the example of supported regular expression characters in Windows PowerShell

Following is the example of supported character classes in Windows PowerShell

Let’s take a look at few standard expression that will be used in powershell.

SubexpressionMatches
^Matches the beginning of the line.
$Matches the end of the line.
.Matches any single character except newline. Using m option allows it to match the newline as well.
[…]Matches any single character in brackets.
[^…]Matches any single character not in brackets.
\ABeginning of the entire string.
\zEnd of the entire string.
\ZEnd of the entire string except allowable final line terminator.
re*Matches 0 or more occurrences of the preceding expression.
re+Matches 1 or more of the previous thing.
re?Matches 0 or 1 occurrence of the preceding expression.
re{ n}Matches exactly n number of occurrences of the preceding expression.
re{ n,}Matches n or more occurrences of the preceding expression.
re{ n, m}Matches at least n and at most m occurrences of the preceding expression.
a| bMatches either a or b.
(re)Groups regular expressions and remembers the matched text.
(?: re)Groups regular expressions without remembering the matched text.
(?> re)Matches the independent pattern without backtracking.
\wMatches the word characters.
\WMatches the nonword characters.
\sMatches the whitespace. Equivalent to [\t\n\r\f].
\SMatches the nonwhitespace.
\dMatches the digits. Equivalent to [0-9].
\DMatches the nondigits.
\AMatches the beginning of the string.
\ZMatches the end of the string. If a newline exists, it matches just before newline.
\zMatches the end of the string.
\GMatches the point where the last match finished.
\nBack-reference to capture group number “n”.
\bMatches the word boundaries when outside the brackets. Matches the backspace (0x08) when inside the brackets.
\BMatches the nonword boundaries.
\n, \t, etc.Matches newlines, carriage returns, tabs, etc.
\QEscape (quote) all characters up to \E.
\EEnds quoting begun with \Q.

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.