PowerShell – Writing Regular Expressions
A regular expression is a string, written using a special regular expression language, that helps a computer identify strings that are of a particular format—such as an IP address, a UNC, or an e-mail address. A well-written regular expression has the ability to allow a Windows PowerShell script to accept as valid or reject as invalid data that does not conform to the format you’ve specified.
The Windows PowerShell –match operator compares a string to a regular expression and then returns either True or False depending on whether the string matches the regex.
Here is an example of a simple match
PS C:\> "WinAdmin.org" -match "WIn" True PS C:\> "WinAdmin.org" -match "windows" False
By default, a regex is case-insensitive in PowerShell. But if you want to match case sensitive, you can use -cmatch
PS C:\> "WinAdmin.org" -cmatch "admin" False PS C:\> "WinAdmin.org" -cmatch "Admin" True
Regular Expressions – Wildcards and Repeaters
A regex can contain a few wildcard characters.
. (period) – matches one instance of any character
? (question mark) – matches zero or one instance of any character
* matches zero or more of the specified characters
+ matches one or more of the specified characters.
PS C:\> "hello" -match "h.llo" True PS C:\> "hello" -match "h?ello" True PS C:\> "hello" -match "h?llo" True PS C:\> "hello" -match "h*o" True PS C:\> "hello" -match "hel+o" True
Regular Expressions – Character Classes
- \w matches any word character, meaning letters and numbers.
- \s matches any white space character, such as tabs, spaces, and so forth.
- \d matches any digit character.
PS C:\> "Windows Server" -match "\w" True PS C:\> "Windows Server" -match "\w\s\w" True PS C:\> "Windows Server" -match "\d" False PS C:\> "Windows Server 2016" -match "\d" True
Regular Expressions – Character Groups, Ranges, and Sizes
A regex can also contain groups or ranges of characters, enclosed in square brackets. For example, [aeiou] means that any one of the included characters—a, e, i, o, or u—is an acceptable match. [a-zA-Z] indicates that any letter in the range a-z or A-Z is acceptable
PS C:\> "Windows" -match "Win[def]ows" True
Creating a regular expression to check IP.
PS C:\> "192.168.0.1" -match "\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}" True PS C:\> "192.168.0.A" -match "\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}" False