SoFunction
Updated on 2025-03-10

Using regular expressions to match string instances in PowerShell

This article introduces the use of the match operator in PowerShell to extract the specified content from a string in conjunction with regular expressions.

Using regular expressions, in addition to determining whether a string matches a certain regular expression rule, another very important application is to extract the specified content from the string. What does it mean? For example, there are three consecutive numbers in a string. We want to extract these three numbers very conveniently, so we can use regular expressions.

Copy the codeThe code is as follows:

PS C:\Users\Hong> $str="abc123abc"
PS C:\Users\Hong> $pattern="(\d{3})"
PS C:\Users\Hong> $str -match $pattern
True
PS C:\Users\Hong> $matches

Name                           Value
----                           -----
1                              123
0                              123


In the above example, we specify a string $str="abc123abc", which contains three consecutive numbers 123. We have defined another $pattern variable, which is a regular expression. When we run match directly, the output is true, indicating that there are three consecutive numbers in the $str string.
When we run $matches again, we output 123, which is the matching value. The $matches variable is not customized by us, it is a system variable. When we run the match operator, this system variable automatically gets the value.

Let’s talk about why $matches has two values. Let’s modify the above example. Let's see the difference.

Copy the codeThe code is as follows:

PS C:\Users\Hong> $str="abc123abc"
PS C:\Users\Hong> $pattern="abc(\d{3})"
PS C:\Users\Hong> $str -match $pattern
True
PS C:\Users\Hong> $matches

Name                           Value
----                           -----
1                              123
0                              abc123


We modified the value of the $pattern variable and added an abc in front of it. The value of this in $matches[0] becomes abc123. This means that $matches[0] represents what matches the regular expression. The contents of $matches[1] and the following are the contents matched in brackets of the regular expression. In the example we only have one bracket, and that is only $matches[1]. Just imagine if the regular expression has several brackets, there will be multiple $matches element values.

This article introduces so much about PowerShell using match to extract the specified content in a string. I hope it will be helpful to you. Thank you!