Regular Expressions

In powershell you can use -match or -notmatch to identify string patterns using regular expression characters:

Match exact characters anywhere in the original string:
PS C:> "Ziggy stardust" -match "iggy"

A period . will match a single character:
PS C:> "cat" -match "c.t"
PS C:> "Ziggy stardust" -match "s..rdust"

Match any (at least one) of the characters - place the options in square brackets [ ]
PS C:> "Ziggy stardust" -match "Z[xyi]ggy"

Match a range (at least one) of characters in a contiguous range [n-m]
PS C:> "Ziggy stardust" -match "Zigg[x-z] Star"

Match any but these, a caret (^) will match any character except those in brackets
PS C:> "Ziggy stardust" -match "Zigg[^abc] Star"

Match the beginning characters: ^
PS C:> "Ziggy stardust" -match "^zig"

Match the end characters: $
PS C:> "Ziggy stardust" -match "dust$"

Match zero or more instances of the preceding character: *
PS C:> "Ziggy stardust" -match "g*"

Match zero or one instance of the preceding character: ?
PS C:> "Ziggy stardust" -match "g?"

Match the character that follows as an escaped character
PS C:> "Ziggy$" -match "Ziggy\$"

Match any character in a character class: \p{name}
Supported names are Unicode groups and block ranges for example, Ll (Letter, Uppercase), Nd (Number, Decimal Digit), Z (All separators), IsGreek, IsBoxDrawing.

PS C:> "ZiGGY Stardust" -match "\p{Ll}+"

Match text not included in groups and block ranges: \P{name} .

PS C:> 1234 -match "\P{Ll}+"

Match any word character: \w This is equivalent to [a-zA-Z_0-9]

PS C:> "Ziggy stardust" -match "\w+"

Match any nonword character \W This is equivalent to [^a-zA-Z_0-9]

PS C:> "Ziggy stardust" -match " \W+"

Match any white-space: \s This is equivalent to [ \f\n\r\t\v]

PS C:> "Ziggy stardust" -match "\s+"

Match any non-white-space: \S This is equivalent to [^ \f\n\r\t\v]

PS C:> "Ziggy stardust" -match "\S+"

Match any decimal digit: \d This is equivalent to \p{Nd} for Unicode and [0-9] for non-Unicode

PS C:> 12345 -match "\d+"

Match any nondigit: \D This is equivalent to \P{Nd} for Unicode and [^0-9] for non-Unicode

PS C:> "Ziggy stardust" -match "\D+"

In addition to the above Powershell also supports the quantifiers available in .NET regular expressions, these allow even more specific criteria such as: the string must match at least 5, but no more than 10 items.

The .Net framework uses a traditional NFA regex engine, to learn more about regular expressions look for the book Mastering Regular Expressions by Jeffrey Friedl

“Mere enthusiasm is the all in all. . . .Passion and expression are beauty itself.” - William Blake

Related:
Comparison -like, -lt, -gt, -eq, -ne, -match
Wildcards - Match multiple items



Back to the Top

© Copyright SS64.com 1999-2010
Some rights reserved