0
0
PowerShellscripting~5 mins

Common regex patterns in PowerShell

Choose your learning style9 modes available
Introduction
Regular expressions help you find or check text patterns quickly and easily.
Checking if an email address is valid.
Finding phone numbers in a document.
Extracting dates from text.
Replacing certain words in a file.
Validating user input like zip codes.
Syntax
PowerShell
Select-String -Pattern '<regex_pattern>' -Path '<file_path>'

# Or use -match operator:
$string -match '<regex_pattern>'
Use single quotes around regex patterns to avoid unwanted variable expansion.
The -match operator returns True if the pattern is found in the string.
Examples
Checks if the string contains one or more digits.
PowerShell
'hello123' -match '\d+'
Validates a simple email pattern.
PowerShell
'test@example.com' -match '^[\w.-]+@[\w.-]+\.\w{2,}$'
Searches for a pattern like a Social Security number in a file.
PowerShell
Select-String -Pattern '\b\d{3}-\d{2}-\d{4}\b' -Path 'data.txt'
Sample Program
This script looks for an email and a phone number in the text and prints them if found.
PowerShell
$text = 'Contact me at user@example.com or call 123-456-7890.'

if ($text -match '[\w.-]+@[\w.-]+\.\w{2,}') {
    Write-Output "Found an email address: $($matches[0])"
}

if ($text -match '\d{3}-\d{3}-\d{4}') {
    Write-Output "Found a phone number: $($matches[0])"
}
OutputSuccess
Important Notes
Remember to escape special characters like dot (.) and backslash (\) in regex patterns.
PowerShell stores the last match in the automatic variable $matches.
Regex patterns are case-insensitive by default with -match; use -cmatch for case-sensitive matching.
Summary
Regular expressions help find text patterns easily.
Use -match operator or Select-String cmdlet in PowerShell.
Common patterns include digits, emails, and phone numbers.