PowerShell: How to Use Regex to Capture All Matches


You can use the following basic syntax in PowerShell to capture all Regex matches in a particular string:

$m = ([regex]'A...').Matches($id_list)

This particular example captures all matches of the pattern ‘A…’ (the capital letter A followed by three characters) in the string variable named $id_list and stores the result in a variable named $m.

You can then access specific matches by using the following syntax:

$m[1].Value

This particular example will return the matching text of the second occurrence of the Regex pattern found in the string.

The following example shows how to use this syntax in practice.

Example: How to Use Regex to Capture All Matches in PowerShell

Suppose that we have the following string that contains several employee ID’s:

  • ‘EmployeeA005 EmployeeA006 EmployeeA015’

Suppose that we would like to extract each pattern that matches the A followed by three numbers.

We can use the following syntax to do so:

$id_list = 'EmployeeA005 EmployeeA006 EmployeeA015'
$m = ([regex]'A...').Matches($id_list)

We can use the following syntax to display all matching patterns that were found:

$m | % {$_.Value}

The following screenshot shows how to use this syntax in practice:

PowerShell regex match all

We can see that the variable $m contains all three matching Regex patterns:

  • A005
  • A006
  • A015

We could also use the following syntax to access a specific occurrence of one of the matching Regex patterns:

$m[1].Value

The following screenshot shows how to use this syntax in practice:

PowerShell Regex match all and extract specific occurrence

Notice that this returns only the second occurrence of the matching Regex pattern, which turns out to be A006.

Related Tutorials

The following tutorials explain how to perform other common tasks in PowerShell:

PowerShell: Use Select-String to Search for Multiple Patterns
PowerShell: Use Select-String to Recursively Search for Strings
PowerShell: Use Select-String with Exact Match

Leave a Reply