Regular Expressions in PowerShell

Master regex in PowerShell for pattern matching, text extraction, validation, and string manipulation with practical real-world examples.

📖 3 min read📅 2026-02-10Advanced Topics

Regex Basics in PowerShell

Regular expressions (regex) are powerful pattern-matching tools. PowerShell provides several ways to use them.

The -match Operator

# Basic matching
"Hello World" -match "World"          # True
"Hello World" -match "world"          # True (case-insensitive)
"Hello World" -cmatch "world"         # False (case-sensitive)
 
# Access the match
"Error: File not found" -match "Error: (.+)"
$Matches[0]    # "Error: File not found" (full match)
$Matches[1]    # "File not found" (capture group)

Common Regex Patterns

# Character classes
"abc" -match "[a-z]+"         # Letters
"123" -match "\d+"            # Digits
"hello world" -match "\w+"   # Word characters
"  " -match "\s+"             # Whitespace
 
# Anchors
"Hello" -match "^Hello$"     # Exact match
"Hello World" -match "^Hello" # Starts with
"Hello World" -match "World$" # Ends with
 
# Quantifiers
"aaa" -match "a{3}"          # Exactly 3
"aaa" -match "a{2,4}"        # 2 to 4
"aaa" -match "a+"            # 1 or more
"" -match "a*"               # 0 or more
"a" -match "a?"              # 0 or 1

Named Capture Groups

$logLine = "2026-02-10 14:30:15 ERROR Database connection failed"
 
$logLine -match "(?<date>\d{4}-\d{2}-\d{2}) (?<time>\d{2}:\d{2}:\d{2}) (?<level>\w+) (?<message>.+)"
 
$Matches.date     # "2026-02-10"
$Matches.time     # "14:30:15"
$Matches.level    # "ERROR"
$Matches.message  # "Database connection failed"

Practical Regex Validations

# Email validation
function Test-Email {
    param([string]$Email)
    $Email -match "^[\w.+-]+@[\w-]+\.[\w.]+$"
}
 
Test-Email "user@example.com"     # True
Test-Email "invalid-email"         # False
 
# IP address validation
function Test-IPv4 {
    param([string]$IP)
    $IP -match "^((25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(25[0-5]|2[0-4]\d|[01]?\d\d?)$"
}
 
# Phone number extraction
$text = "Call us at (555) 123-4567 or 555.987.6543"
$pattern = "\(?\d{3}\)?[-.\s]?\d{3}[-.\s]?\d{4}"
[regex]::Matches($text, $pattern) | ForEach-Object { $_.Value }

Using [regex] Class

# Multiple matches
$text = "Errors: E001, E002, E003"
[regex]::Matches($text, "E\d{3}") | ForEach-Object { $_.Value }
# Output: E001, E002, E003
 
# Replace with function
$result = [regex]::Replace("hello world", "\b\w", { $args[0].Value.ToUpper() })
# "Hello World"
 
# Split with regex
[regex]::Split("one,,two,,,three", ",+")
# @("one", "two", "three")

Select-String (grep for PowerShell)

# Search files for a pattern
Select-String -Path "*.log" -Pattern "ERROR|CRITICAL"
 
# Search recursively
Get-ChildItem -Recurse -Filter "*.ps1" | Select-String "TODO|FIXME"
 
# Show context (lines before/after match)
Select-String -Path "app.log" -Pattern "Exception" -Context 3, 3
 
# Count matches
(Select-String -Path "access.log" -Pattern "404").Count

Exercises

  1. Write a regex to validate passwords (8+ chars, uppercase, lowercase, digit, special char)
  2. Extract all URLs from a block of text
  3. Parse a log file and group errors by type
  4. Use regex to find and replace dates from MM/DD/YYYY to YYYY-MM-DD format
  5. Build a script that validates CSV data (emails, phone numbers, zip codes)

This concludes the PowerShell tutorial series! Check out our Bash tutorials next.