Using Regular Expressions in PowerShell Part I

Part I out of II of Using Regular Expressions in PowerShell. Regular expressions are strings that describe a search pattern. Depending on the type of search at hand will determine the regular expression needed. In this tutorial, you will learn how to use regular expressions in PowerShell scripts.

Setup

If you have not already done so, click open Windows PowerShell ISE.

Step one.

In order to use regular expressions in PowerShell, you will need to learn how to create regular expressions. Windows PowerShell is built from the .NET Framework, so when you use regular expressions in Windows PowerShell, you are actually using the Regex .NET class. Taking this into consideration, you can use any documentation and example of regular expressions in .NET and apply it to PowerShell.

The most direct way to use regular expressions is to use the Regex object's methods directly. You can check whether a string contains a particular character or substring by applying code such as the one below:

Example

#String Search with Regex
#[Regex]::IsMatch("I love to garden.","garden")
    

Copy and Try it

The code above seeks whether the string "I love to garden" contains the string "garden". If it does, it will return the Boolean value, TRUE; however when it does not, it will return the Boolean value, false. The output is presented below.

In this particular example, "garden" is a simple regular expression using what is known as literal characters.

Step two.

One can place any kind of regular expression they wish in place of, "garden" to do the search. Below is another example of a regex search:

Example


#Digit Search with Regex
[Regex]::IsMatch("I bought 6 apples.","[0-9]")
    

Copy and Try it

The output is presented in the image below:

The regex here is more powerful than the first example. "[0-9]" means "match any digit from 0-9," which in this case will match the 6. If you tried to do this using the string's IndexOf method, you would have ten separate calls for IndexOf to look for each character separately. In short, more work then needed.

The actual regular expressions are the second parameter in the IsMatch method. The first parameter is simply the string you want to search to search in.

Remarks last but not least…

There are various applications to today's lesson, it just depends on what you expect of the output. Thank you for being a valued reader. Join us next time for Part II of Using Regular Expressions in PowerShell…