Skip to content
Tutorials Center
My learning

Topics

Lesson 22 of 34 ยท Files, Data and Errors

Regular Expressions and Text Processing

Use regular expressions in PowerShell: the -match and -replace operators, the $Matches variable, Select-String, named groups and [regex]::Matches for log files.

Even in a world of objects, text keeps arriving: log files, command output from native programs, configuration lines, web pages. Regular expressions (regex) describe text patterns, and PowerShell uses them in several places: the -match and -replace operators, -split, switch -Regex, the Select-String cmdlet, and the .NET [regex] class. They all use the .NET regex engine, so one pattern syntax works everywhere.

This lesson assumes you know the basics of patterns (character classes, quantifiers, groups); if not, the Linux regular expressions lesson covers the ideas, though the syntax details differ a little between engines. The PowerShell commands are shown read-only, and the runnable examples are JavaScript RegExp stand-ins: the pattern syntax in these examples is the same in both, but JavaScript's API and defaults are different, and the model code points out where.

Where regex appears

-match Test a string, fill $Matches.
-replace Rewrite text with $1 groups.
Select-String Search files line by line.
[regex] Get every match as an object.

One .NET engine behind all four.

1 / 2

The -match operator and $Matches

-match tests whether a string matches a pattern and returns $true or $false. When the left side is a single string and the match succeeds, PowerShell also fills the automatic hashtable $Matches:

POWERSHELL
$line = '2025-03-14 12:01:09 ERROR payment failed (order 4417)'

if ($line -match '(\d{4})-(\d{2})-(\d{2})') {
    $Matches[0]    # 2025-03-14   (the whole match)
    $Matches[1]    # 2025         (first group)
}

if ($line -match '(?<level>ERROR|WARN|INFO)\s+(?<text>.+)$') {
    $Matches.level   # ERROR
    $Matches.text    # payment failed (order 4417)
}

Key facts:

  • Case-insensitive by default. Use -cmatch for case-sensitive matching. The same pair exists for -replace/-creplace and -split/-csplit.
  • -match finds the first match only. For all matches use Select-String -AllMatches or [regex]::Matches.
  • $Matches is a hashtable: plain groups use integer keys, and named groups ((?<name>...)) use their name as key, so $Matches.level is far easier to read than $Matches[2].
  • If the left side is an array, -match works as a filter and returns the matching elements; $Matches is not set then.
POWERSHELL
'error','warning','Error 2' -match '^error'    # error, Error 2

Remember that . matches any character, so escape literal dots and special characters with a backslash or [regex]::Escape(), and anchor patterns with ^ and $ when you need a full-string test.

Searching files with Select-String

Select-String is PowerShell's grep. It reads files (or piped text) line by line and returns MatchInfo objects with Filename, LineNumber, Line and Matches properties:

POWERSHELL
Select-String -Path .\logs\*.log -Pattern 'ERROR'
Select-String -Path .\logs\*.log -Pattern 'ERROR' -CaseSensitive
Select-String -Path .\app.log -Pattern 'timeout' -Context 2,1      # 2 lines before, 1 after
Select-String -Path .\app.log -Pattern '\b\d{3}\b' -AllMatches
Select-String -Path .\app.log -Pattern 'a.b' -SimpleMatch          # literal, no regex
'x=1', 'y=2' | Select-String 'y'

Because the output is objects, you can keep working on it:

POWERSHELL
Select-String -Path .\logs\*.log -Pattern 'ERROR' |
  Group-Object Filename |
  Sort-Object Count -Descending |
  Select-Object Name, Count

Use -NotMatch to invert the test, and -List to stop after the first match in each file.

Replacing text with -replace

-replace takes a regex and a replacement and returns the changed string (it never modifies the original variable):

POWERSHELL
'2025-03-14' -replace '(\d+)-(\d+)-(\d+)', '$3/$2/$1'     # 14/03/2025
'  too   many   spaces ' -replace '\s+', ' '             # " too many spaces "
'[email protected]' -replace '^[^@]+', '***'               # ***@example.com
'build-42' -replace '(?<n>\d+)', '[${n}]'                 # build-[42]

The replacement uses $1, $2 or ${name} for groups, which is exactly why you must use single quotes: inside double quotes PowerShell expands $1 as a variable (empty) before -replace ever sees it. If the replacement itself contains a literal $, write $$. In PowerShell 6 and later the replacement can also be a script block that receives the match, which helps when the new text must be computed.

The [regex] class

For several matches, or for an option the operators lack, use .NET directly:

POWERSHELL
$text = 'ids: 17, 204, 9'
[regex]::Matches($text, '\d+') | ForEach-Object { [int]$_.Value }      # 17 204 9
[regex]::Replace($text, '\d+', { param($m) [int]$m.Value * 2 })        # ids: 34, 408, 18
[regex]::Escape('1+1=2?')                                              # 1\+1=2\?
[regex]::IsMatch('abc', '^[a-c]+$')                                    # True

Each result of [regex]::Matches is a Match object with Value, Index, Length and Groups.

Practice: matching a log format

The model below imitates -match with a pattern and a $Matches hashtable. JavaScript's RegExp is case-sensitive unless you pass the i flag, so the model adds i to copy PowerShell's default.

JS A -match model with $Matches and named groups

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The same pattern text would work unchanged in PowerShell (apart from escaping the backslashes the way a JavaScript string needs). When a pattern uses only named groups, $Matches holds key 0 plus the names; with plain groups it holds 0, 1, 2 and so on (the model skips patterns that mix both styles). A failed match leaves no $Matches for that test.

Practice: a small log parser

This second stand-in does what a Select-String plus Group-Object pipeline would do: parse every line, count levels, find the most frequent error text and rewrite sensitive data with -replace.

JS Parsing a log: match, group and replace

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Lines that do not fit the format are counted and skipped instead of crashing the parser, which is the right habit for real logs. In PowerShell the equivalent would use Select-String, Group-Object and [regex]::Matches; JavaScript's matchAll plays the role of [regex]::Matches here.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is the result of 'Hello' -match 'hello'?

    -match ignores case unless you use -cmatch.
  2. 2. Which line correctly swaps the groups in a date like 2025-03-14 to 14/03/2025?

    The replacement string must be in single quotes so $1, $2 and $3 reach -replace instead of being expanded as (empty) variables in double quotes.
  3. 3. How do you read a named group called level after a successful -match?

    $Matches is a hashtable. Named groups are keys, so $Matches.level or $Matches['level'] work.
  4. 4. You need every number in a string, not only the first. Which approach fits?

    -match stops at the first match. [regex]::Matches and Select-String -AllMatches return every match as an object.

Summary

  • -match returns a Boolean and fills $Matches (including named groups) for a single string; with an array on the left it filters instead.
  • Comparison and replace operators ignore case by default; -cmatch, -creplace and -csplit are case-sensitive.
  • Select-String searches files and returns MatchInfo objects with Filename, LineNumber, Line and Matches.
  • -replace uses $1 or ${name} in the replacement, so write it in single quotes.
  • [regex]::Matches, [regex]::Replace and [regex]::Escape give you all matches, computed replacements and safe literals.

Next, put PowerShell to work on the machine itself in Processes, Services and the System.