🎓 A1Learner
🔍
0 of 47 lessons completed

PowerShell Regular Expressions in Depth

A regular expression is a pattern that describes text to find. The pattern can match whole words, digits, or parts of a string.

Keep parts with capture groups

Each pair of parentheses keeps one part. Read the parts back from $Matches by number.

$found = "order42" -match "([a-z]+)([0-9]+)"
$Matches[0]
$Matches[1]
$Matches[2]

Swap matched text with -replace

The pattern says what to swap, and the second value says what to put in its place.

"hello world" -replace "world", "Ana"
"abc123def" -replace "[0-9]+", "#"

Name a group to read it back

A name inside (?<name>...) labels the group. Read it back from $Matches by that name.

$found = "order42" -match "(?<word>[a-z]+)(?<num>[0-9]+)"
$Matches["word"]
$Matches["num"]

Example

$text = "Ana-31"
$ok = $text -match "(?<name>[a-zA-Z]+)-(?<age>[0-9]+)"
$Matches["name"]
$Matches["age"]
"Hello" -match "hello"
"Hello" -cmatch "hello"

Key points

  • Match operator: Use -match to test whether text fits a pattern.
  • Capture group: Parentheses in a pattern mark one part of the match to keep.
  • Matches variable: $Matches holds the captured parts, with [0] for the whole match and [1] for the first group.
  • Named group: A group written as (?<name>...) can be read back by its name.
  • Replace operator: Use -replace to swap every part that fits a pattern for new text.

In this example, the pattern splits Ana-31 into a named name part and a named age part. The two case tests at the end show that -match ignores case while -cmatch does not.

Note

-match ignores case by default, while -cmatch treats upper and lower case as different.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

After "abc123" -match "([a-z]+)([0-9]+)", what does $Matches[1] hold?