PowerShell Regular Expressions

Regular expressions with -match, -replace operators and .NET regex classes.

Regex Quick Reference

Match operator
"10.50.1.20" -match '\d+\.\d+\.\d+\.\d+'    # True
$Matches[0]                                     # 10.50.1.20
Named captures
"User: AdminErosado logged in at 14:30" -match 'User: (?<user>\w+) logged in at (?<time>\d+:\d+)'
$Matches.user    # AdminErosado
$Matches.time    # 14:30
Replace with regex
"Error: 404 Not Found" -replace '\d+', 'XXX'    # Error: XXX Not Found
"2026-04-10" -replace '(\d{4})-(\d{2})-(\d{2})', '$2/$3/$1'    # 04/10/2026
Select-String (grep equivalent)
Select-String -Path *.log -Pattern "ERROR|FATAL"
Select-String -Path *.log -Pattern "Failed.*login" -CaseSensitive
Get-Content auth.log | Select-String -Pattern '\d+\.\d+\.\d+\.\d+' -AllMatches | ForEach-Object { $_.Matches.Value }
Split with regex
"one,two,,three" -split ','           # @("one","two","","three")
"one   two   three" -split '\s+'     # @("one","two","three")
Validate patterns
# IP address
"10.50.1.20" -match '^(\d{1,3}\.){3}\d{1,3}$'

# Email
"admin@domusdigitalis.dev" -match '^[\w.+-]+@[\w-]+\.[\w.]+$'

# MAC address
"14:F6:D8:7B:31:80" -match '^([0-9A-F]{2}:){5}[0-9A-F]{2}$'

See Also