0
0
PowerShellscripting~5 mins

Regular expressions with -match in PowerShell

Choose your learning style9 modes available
Introduction

Regular expressions help you find patterns in text. The -match operator checks if text fits a pattern.

Check if a user's input contains a phone number.
Find if a file name has a certain extension like .txt or .csv.
Search logs for error messages with specific codes.
Validate if an email address looks correct.
Extract parts of a string like dates or words.
Syntax
PowerShell
string -match pattern

string is the text you want to check.

pattern is the regular expression you want to match.

Examples
Checks if 'World' is in the string 'Hello World'. Returns True.
PowerShell
'Hello World' -match 'World'
Checks if the string matches three digits, a dash, then three digits.
PowerShell
'123-456' -match '\d{3}-\d{3}'
Checks if the string starts with the letter 'a'.
PowerShell
'apple' -match '^a'
Checks if the string looks like an email ending with .com.
PowerShell
'test@example.com' -match '\w+@\w+\.com'
Sample Program

This script looks for a phone number pattern in the text. If found, it prints the number.

PowerShell
$text = 'My phone number is 555-1234'
if ($text -match '\d{3}-\d{4}') {
    Write-Output "Found a phone number: $($matches[0])"
} else {
    Write-Output 'No phone number found.'
}
OutputSuccess
Important Notes

The -match operator sets a special variable $matches with the found text.

Regular expressions use special symbols like \d for digits and ^ for start of string.

Matching is case-insensitive by default in PowerShell.

Summary

-match checks if text fits a pattern.

Use $matches to get the matched part.

Regular expressions help find complex text patterns easily.