Powershell

Regular Expressions (Regex) in PowerShell

PowerShell is a Windows configuration management and task automation program. It has more power than all other Windows management tools. Because it can manage the hidden tasks in Windows that are not visible to other tools. PowerShell has the ability to manage regular expressions. It can edit, replace, delete, or match the regular expressions using various commands, or operators.

Quick Outline:

Regular Expressions (Regex) in PowerShell – Practically Explained

PowerShell regular expressions (regex) are a series of characters that are used to search text patterns in the given text. Its job is to identify the matching text patterns. PowerShell regex is case-insensitive by default, meaning that it ignores the case sensitivity such as upper or lower case, and matches the text pattern. It has the capability to match single and multiple text patterns as well.

PowerShell regex has a special set of characters that matches the strings or set of strings using specialized syntax. It is used to search, edit, and manage text, strings, or data. It is one of the most powerful ways to work with the strings. Regex acts like a pattern validator when it is asked to find the pattern.

People are afraid of regex because of its complex expressions. Even when I first researched it I got confused and closed the tab because of its complexity. But, then, I read about it and was amazed at the power it has. But, it’s true whoever sees the regular expressions for the first time may think of it as the 3 year old kid pressing the keyboard several times. It can get the work done in one line when other programming languages take hundreds of lines of code.

PowerShell regex uses the shorthand language model. It uses special characters called metacharacters. Any metacharacter in regex has a special meaning, such as full stop. The full stop (.) matches any character in a pattern except the new line.

Regular Expression (Regex) Cheat Sheet

Regular expressions (Regex) characters along with their descriptions are mentioned in the table below:

Regular Expression (Regex) Characters Description
\s Matches the whitespace character
\S Matches the characters that are non-whitespace
\d Matches the digits ranging from zero to nine
\D Matches non-digits
\w Matches the characters of the word
\W Matches the non-word characters
\n Matches the newline
\t Matches with a tab
\r Matches with a carriage return
\A Makes a match with the beginning of the entire string
\b Matches the word boundary ranging from word and a non-word character
\B Matches non-word boundaries
\E Terminates the quoting that begins with \Q
\G Matches the point in the pattern where the last pattern ended
\Q It escapes all the characters up to \E
\z Matches the string’s ending
\Z If there exists a newline then, it matches the character just before the line.
. Makes a match with a single character despite a newline
$ Makes a match with the line’s end
^ Makes a match with the start of the line
* Make a match 0 or more times. It matches the pattern as many times as possible
\ It escapes the special character
+ Make a match one or more times
? It repeats at least 0 or 1 times
?? It repeats 0 or 1 time, a minimum of 0 times, if possible
+? It repeats one or more than one time
*? It repeats zero or more than one time
[a-z] It matches the character within the given range of characters.
[abc1234…] It matches any character that is located within brackets.
[^abc1234…] It matches any character outside brackets.
a|b It makes a match with either a or b
{n} It makes a match of exactly n times.
{n,} It makes a match of at least n times.
{n,m} It makes a match of n times up to n times.
(…) It specifies the pattern as a group.

How Regular Expressions (Regex) Work with PowerShell Commands?

The regular expressions (regex) require two things to work. One is the text pattern to be searched, and the second is the pattern where you will search for your desired pattern. There are several commands and patterns that are suitable to work, such as the -Match operator, -Replace operator and Select-String command.

Find the Matching Patterns using Regex in PowerShell (-Match Operator)

The -Match operator is one of the comparison operators. It finds the match between a certain regular expression and a string. In general, it finds the input that matches with the regex pattern. The -Match operator is often used with conditional statements. If the string value matches then it returns the boolean value True, it returns False. Get to know more about the -Match operator by reading this article.

Syntax

This is the syntax of the -Match operator in PowerShell:

[input-text-you-want-to-match-with] -match [input-text-you-want-to-match]

Example 1: Matches an Exact Character in the Given Value

This example will provide the demonstration to match the exact character in the provided string value:

"beautiful" -match "ful"

Example 2: Match a Single Character in the Given Value Using Full Stop (.) Regular Expression

This example will demonstrate the matching of any single character in the given value by using the. character:

"pretty" -match "p....y"

Example 3: Matches at least one Character Within the Brackets Using [abc…] Regular Expression

This example will demonstrate how to match at least a single character within the brackets:

"Try" -match "T[rst]y"

Example 4: Matches the Characters Except Specified in Brackets Using [^abc…] Regular Expression

In this demonstration the regex will make a match with all the characters outside the bracket only:

"All" -match "[^int]ll"

Example 5: Matches the Beginning of the Characters Using the ^ Regular Expression

In this example, the regular expression will match only the beginning characters of the string:

"Copy" -match "^co"

Find the Matching Text Patterns and Replace them Using -Replace Operator

Just like the -Match operator, the -Replace operator finds the text or pattern in the given string value. However, unlike the -Match operator, it replaces the matched text pattern. Learn more about the -Replace operator by reading this article.

Syntax

This is the syntax for the -Replace operator in PowerShell:

[input-text] -replace [regex], [text-substitute]

Example: Use the -Replace Operator to Find and Replace the Regular Expressions

This article will provide a demonstration to find and replace the regular expressions using the -Replace operator:

$greetings = "Good Night, Billy"

$greetings -replace "Good Night", "Good Morning"

According to the above code:

  • First, initialize a variable and assign a string having two substrings separated by a comma.
  • Then, in the next line, place the variable along with the -replace parameter.
  • After that, assign two regular expressions.
  • First, regular expressions will find the text pattern in the string.
  • The second regular expression will replace the found string.

Select the Matching String or Patterns with Regex (Select-String)

The Select-String command searches for patterns through strings and files. It selects the text or pattern in the provided string. The other name for the Select-String command is the Grep equivalent command. The Select-String command uses the regular expressions (regex) to match the strings and files in the given pattern. Unlike the -Match operator, it uses the -Pattern parameter to match the text or pattern in a string. Get to know more about the Select-String command by reading this article.

Syntax

This is the syntax of the Select-String command in PowerShell:

[Input-File or folder location-or any command] | Select-String -Pattern [String to be searched]

Example: Select and Display the Text Pattern Using Select-String Command

This example will demonstrate the method to use the -Pattern regular expression to select and display the text pattern:

Get-Process | Select-String -Pattern 'win'

According to the above code:

  • First, provide any input, such as folder location, text, or any command of your choice.
  • Then, pipe it to the Select-String command.
  • After that, use the -Pattern parameter and specify the regular expression you want to select:

What are the Building Blocks of Regular Expressions (Regex)?

The listed items are the building blocks of the Regular Expression (Regex):

  1. Literals: Matches the same value in the pattern
  2. Groups: Patterns can be grouped by placing round braces around them
  3. Operator: An operator is used to perform mathematical or logical operations. Examples of operators include assignment or arithmetic operators
  4. Ranges: Add the consecutive characters in the character class. to specify the range, use the dash operator [0-9]
  5. Quantifier: Limits the instances of every element that must be present in the input string

What are the Applications of Regular Expressions (Regex)?

These are the applications of the Regular Expression (Regex):

  1. Regular expressions (regex) help in data extraction
  2. It can split a string into various tokens
  3. It verifies the structure of strings
  4. Regex can perform the pattern validation in the form
  5. Regex can search, replace, and rearrange the parts of the string

What are the Limitations of the Regular Expressions (Regex)?

There are no limitations of Regex, however, some of them are listed below:

  1. Regex can match a single word only
  2. It can not match multiple words at a time
  3. In regex, only letters can be searched
  4. There is no information stored about line breaks in regex
  5. There are readability issues in the regex
  6. Regex is not made for simple tasks or for complex tasks

Conclusion

Regular Expressions or Regex is basically a pattern that is used to match a text. It uses the -Match operator to match the text pattern. The -Match operator returns the Boolean value in return. If the pattern matches, it returns the True value, else it returns the Value False. Basically, it functions in two parts, first, it takes the pattern to be matched and second it searches that pattern in the given text using the -Match operator. A lot of information about regex is provided including its limitations and applications along with practical examples provided in the above guide.

About the author

Muhammad Farhan

I am a Computer Science graduate and now a technical writer who loves to provide the easiest solutions to the most difficult problems related to Windows, Linux, and Web designing. My love for Computer Science emerges every day because of its ease in our everyday life.