Gice

Technology and General Blog

[*]Regular expressions or regex can be complicated for beginners to understand but is a very effective technique to interact with strings. The regex language is a powerful pattern description shortcut and is used to parse and match the text. PowerShell uses regular expressions in a variety of ways. Because the PowerShell commands or cmdlets are so tightly integrated, it is easy to forget to use regex. Maybe, you do not know that some of these commands are already using regex.

PowerShell can work with streams of objects rather than just text. However, it is relatively capable of text processing. If you do any work related to text processing, you will know that the regex is one of the most important concepts in any programming language. In this article, you will show you how to use regex in PowerShell. So, let’s begin!

What is Regex in PowerShell?

A regex is a particular sequence of characters that utilizes a special syntax to assist you in finding or matching strings or a set of strings. Regex is capable of searching, editing, and manipulating data and text. This expression instructs the engine to match the provided text.

Now, we will look at the method of using regex in PowerShell.

Regex with Character Literals in PowerShell

First of all, we will execute a regular expression by using the “-match” operator. This operator takes a regular expression for pattern matching purposes and returns “$true” if the pattern matches.

Now, we will execute our first regex, in which we will check if the “book” matches with the pattern “ok”:

This expression will return true because the book contains the string “ok(“Bo[ok]”).

Regex with Character Group in PowerShell

Next, we will use the [character group] to match multiple characters at once. In the below-given example, a regex “b[iog]” is utilized to match with “big”. Execution of this regex will check out if the characters between “b” and “g” in “big” match with the character group “[iou]” present in the “b[iou]g” regex:

In the next statement, we have added “book,” which does not match the specified regex. Execute it, and let’s see what result this statement is going to show:

> ‘book’ -match ‘b[iou]g’

This expression will return “false” as “book” does not match with the regex “b[iou]g”.

Regex with Various Patterns in PowerShell

A pattern can be a collection of characters. Characters can be numeric [0-9], or ASCII-based [ -~], or alphabetic [A-Z].

This expression will return true as the pattern matches any two-digit number “42”, in our case.

Any decimal digit will match the “d” character class. On the other hand, “D” will match any non-decimal digit.

> ‘Server-01’ -match ‘Server-dd’

The above-given expression will return true if it matches a server name between (Server-01 – Server-99).

Any word character “[a-z A-Z 0-9]” will be matched by the “w” character class. Utilize “W” for matching any non-word character.

The execution of the above-given expression will return true as the pattern “Book” matches the first-word character ‘B‘.

In regex, the period “(.)” is considered as a wildcard character. Except for a new line, it will match any character “(n)”. The below-given expression will return true because the pattern “[a1 ]” matches four characters.

The “s” character class is used to match whitespace. Whereas, “S” or can be utilized for matching non-whitespace characters.

The execution of the above-given expression will return “true” as the pattern “[ – ]” used both methods to match the space.

Regex with Quantifiers in PowerShell

Quantifiers handle the number of times each element should appear in the input string. Some quantifiers available in PowerShell are as follows:

  • [*] is used to specify the occurrence of any element as “zero or more times.
  • [+] is used to specify the occurrence of any element as “one or more times.
  • [?] is used to specify the occurrence of any element as “one or zero times.
  • [n] is used to specify the occurrence of any element exactly as “n times.”
  • n,m is used to specify the occurrence of any element as “at least n times, but no more than m.

The below-given command will return true for any server name, even server names without dashes.

> ‘SERVER01’ -match ‘[A-Z]+-?dd’

Now, we will try to match a phone number with the regex “d3-d3-d4”.

> ‘111-222-3333’ -match ‘d3-d3-d4’

The expression will return “true” if it finds out a correct phone number according to the specified pattern.

In the next part, we will use regex in PowerShell scripts. For that, firstly, open up your Windows PowerShell ISE, and create a new file:

Write out the below-given code for numeric and string matching. In this script, we have stored a pattern in the “$message” variable. In the second line, this “$message” variable will match its value to the “error” regex by using the “-match” operator. We have also added a line of code for numeric pattern matching:

$message = ‘there is an error with your file’
$message -match ‘error’
‘123-45-6789’ -match ‘ddd-dd-dddd’

Save this file as “testfile1.ps1” PowerShell script and execute it by pressing the “Run” button.

Both patterns are matched with the specified regex so that this expression will return “true” for each case.

You can also match a regex to an array. To demonstrate this, we have declared an array “$data” in our script. This array contains some numeric and string values. After adding values to the array, we will match it to a regex: “ddd-dd-dddd“. This statement will check if the array has any numeric values with the pattern specified in the regular expression and print out it on your PowerShell terminal.

$data = @(
           “This is some general text”
           “phone number is 333-99-2222”
           “another text statement”
           “phone number 444-44-4444”
       )
       $data -match ‘ddd-dd-dddd’


The replace operator utilizes regex for pattern matching. This operator searches for a pattern and then replaces it with the other pattern specified in the command. For example, in the below-given script, we have the “$message” variable containing a string value “Hi, my name is Sharqa”. We want to replace “Sharqa” with “Sharqa Hameed”. With the “-replace” operator, we will write out the pattern we want to replace in the first place, and after that, we will add the pattern we want to be replaced.

$message = “Hi, my name is Sharqa”
$message -replace ‘Sharqa’,‘Sharqa Hameed’

Save this “testfile1.ps1” PowerShell script. Execution of this script will output the value of the “$message” variable with the replaced string “Sharqa” with “Sharqa Hameed”.

Conclusion

There are numerous programming concepts where you can use regex or where you may already be using regex without realizing it. PowerShell does an excellent job of incorporating regex features into its language.

With the knowledge gained from this article, you should be able to use regex in PowerShell to match numeric or text patterns while searching for highly complex or specific phrases. We have also shown you how to use the regex quantifier in PowerShell scripts.

Leave a Reply

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