How to Use Regex in PowerShell: Syntax and Examples
In PowerShell, you use regex with operators like
-match and methods like Matches() to find patterns in text. You write regex patterns as strings and use them to test, extract, or replace text easily.Syntax
PowerShell uses regex mainly with the -match operator and the Matches() method. The -match operator returns True if the pattern matches the string. The Matches() method returns all matches as a collection.
string -match 'pattern': Checks ifpatternexists instring.[regex]::Matches(string, 'pattern'): Finds all matches ofpatterninstring.
powershell
$text = 'Hello World' if ($text -match 'World') { 'Match found' } else { 'No match' } $matches = [regex]::Matches($text, 'l+') foreach ($m in $matches) { $m.Value }
Output
Match found
ll
l
Example
This example shows how to check if a string contains digits and how to extract all digit sequences using regex.
powershell
$input = 'Order123 and Invoice456' # Check if string contains digits if ($input -match '\d+') { 'Digits found in string' } # Extract all digit sequences $allMatches = [regex]::Matches($input, '\d+') foreach ($match in $allMatches) { $match.Value }
Output
Digits found in string
123
456
Common Pitfalls
Common mistakes include forgetting to escape special characters in regex patterns and confusing -match with -like. Also, -match returns a boolean, not the matched text directly.
Use $matches[0] after -match to get the first match text.
powershell
# Wrong: Using -like instead of -match 'abc123' -like '*\d*' # Right: Using -match with escaped pattern if ('abc123' -match '\d+') { $matches[0] # Outputs the matched digits }
Output
False
123
Quick Reference
| Operator/Method | Purpose | Example |
|---|---|---|
| -match | Check if pattern exists (returns True/False) | 'abc123' -match '\d+' |
| -notmatch | Check if pattern does NOT exist | 'abc' -notmatch '\d+' |
| [regex]::Matches() | Get all matches as collection | [regex]::Matches('abc123', '\d+') |
| -replace | Replace text matching pattern | 'abc123' -replace '\d+', '456' |
| $matches | Automatic variable holding match info after -match | $text -match 'pattern'; $matches[0] |
Key Takeaways
Use the -match operator to test if a regex pattern exists in a string.
Use [regex]::Matches() to find all matches of a pattern in a string.
Escape special regex characters with double backslashes in PowerShell strings.
After -match, use the automatic $matches variable to access matched text.
Avoid confusing -match (regex) with -like (wildcard matching).