TExcelTAD
Home › PowerShell › PowerShell Regular Expressions

PowerShell Regular Expressions

A regular expression (regex) is a pattern that describes text: "four digits, a dash, two digits", "a word followed by @ and a domain". PowerShell uses the .NET regex engine everywhere: in -match, -replace, -split, switch -Regex, Select-String and the [regex] class.

Pattern basics

Pattern Matches
. any character except newline
\d \w \s a digit, a word character (letter/digit/_), whitespace
\D \W \S the opposites
[abc], [a-z], [^0-9] one character from a set / range / not in it
* + ? 0 or more, 1 or more, 0 or 1
{3}, {2,4} exactly 3, between 2 and 4
^ $ start, end of the text (or line with (?m))
\b word boundary
( ), (?<name> ) capture group, named group
a|b a or b
\. \$ \\ a literal dot, dollar, backslash

-match and $Matches

-match returns True or False for a single string and fills the $Matches hashtable with the first match:

powershell · try it yourself
$entry = 'Order 4711 shipped to Oslo on 2026-03-14'

if ($entry -match '(\d{4})-(\d{2})-(\d{2})') {
    "Whole match: $($Matches[0])"
    "Year $($Matches[1]), month $($Matches[2]), day $($Matches[3])"
}

if ($entry -match 'Order (?<id>\d+) shipped to (?<city>\w+)') {
    "Order $($Matches.id) -> $($Matches.city)"
}

'abc' -match '^\d+
  


'ABC' -cmatch '^[a-z]+
  

Whole match: 2026-03-14
Year 2026, month 03, day 14
Order 4711 -> Oslo
False
False

Named groups ((?<name>…)) make code readable: $Matches.city explains itself. Remember -match is case-insensitive; -cmatch isn't.

Filtering arrays

With an array on the left, -match returns the matching elements (and doesn't set $Matches):

powershell · try it yourself
$emails = 'ada@example.com', 'not-an-email', 'linus@kernel.org', 'grace@@navy.mil'
$emails -match '^[\w.+-]+@[\w-]+\.[\w.]+
  


'---'
$emails -notmatch '@'
ada@example.com
linus@kernel.org
---
not-an-email

-replace with groups

-replace replaces every match. In the replacement string, $1, $2 or ${name} insert captured groups, so always use single quotes for it:

powershell · try it yourself
'2026-03-14' -replace '(\d{4})-(\d{2})-(\d{2})', '$3.$2.$1'
'Smith, John' -replace '(?<last>\w+), (?<first>\w+)', '${first} ${last}'
'too    many     spaces' -replace '\s+', ' '
'Card: 4111111111111234' -replace '\d(?=\d{4})', '*'

# A script block computes each replacement (PowerShell 7)
'price: 10 USD, tax: 2 USD' -replace '\d+', { [int]$_.Value * 100 }
14.03.2026
John Smith
too many spaces
Card: ************1234
price: 1000 USD, tax: 200 USD

(?=…) is a lookahead: it checks what follows without including it in the match. Here it replaces every digit that still has at least four digits after it, which masks all but the last four. The last line shows PowerShell 7's script-block replacement, where $_ is the match object.

Finding all matches: [regex]::Matches

-match only finds the first match. To get them all, use the [regex] class:

powershell · try it yourself
$text = 'Tickets: INC-1001, INC-1042 and CHG-77 were closed; INC-1100 is open.'

$found = [regex]::Matches($text, '(?<type>INC|CHG)-(?<num>\d+)')
$found.Count
$found | ForEach-Object { '{0} #{1}' -f $_.Groups['type'].Value, $_.Groups['num'].Value }

[regex]::Escape('cost (USD) $5.00?')
4
INC #1001
INC #1042
CHG #77
INC #1100
cost\ \(USD\)\ \$5\.00\?

[regex]::Escape() adds backslashes to every special character, so you can safely search for text that came from a user or a file name.

Select-String: grep for PowerShell

Select-String searches text in files or pipeline input and returns MatchInfo objects with the line number, the line and the match:

powershell · try it yourself
Set-Content ./app.log @'
08:00:01 INFO  service started
08:05:12 WARN  slow response 2300ms
08:07:45 ERROR timeout calling payments
08:09:02 INFO  request ok
08:11:30 ERROR disk quota exceeded
'@

Select-String -Path ./app.log -Pattern 'ERROR' | ForEach-Object {
    "line $($_.LineNumber): $($_.Line)"
}

Select-String -Path ./app.log -Pattern '(\d+)ms' | ForEach-Object { $_.Matches[0].Groups[1].Value }
(Select-String -Path ./app.log -Pattern 'info' -CaseSensitive).Count
line 3: 08:07:45 ERROR timeout calling payments
line 5: 08:11:30 ERROR disk quota exceeded
2300
0

Useful switches: -NotMatch (lines that don't match), -SimpleMatch (plain text, no regex), -Context 2,1 (lines before/after), -AllMatches and -List (first match per file).

Splitting with a regex

powershell · try it yourself
'a1b22c333d' -split '\d+'
'key1=value1;key2 = value2' -split '\s*[;=]\s*'
'one,two;three four' -split '[,; ]', 2
a
b
c
d
key1
value1
key2
value2
one
two;three four

The optional third operand limits the number of pieces.

Tip: Test complex patterns step by step, and comment them with the (?x) option, which ignores whitespace and allows # comments inside the pattern.

Test yourself

After 'id=42' -match 'id=(\d+)', what is $Matches[1]?

  1. id=42
  2. 42
  3. id
  4. True

Why should the replacement in -replace '(\w+)@', '$1 at ' use single quotes?

  1. Double quotes are slower
  2. In double quotes PowerShell would expand $1 as a variable before the regex sees it
  3. Single quotes enable regex
  4. There's no difference

Which finds ALL matches of a pattern in a string?

  1. -match
  2. [regex]::Matches($text, $pattern)
  3. $Matches
  4. -like