Introduction
Regular expressions help you find patterns in text. The -match operator checks if text fits a pattern.
Regular expressions help you find patterns in text. The -match operator checks if text fits a pattern.
string -match pattern
string is the text you want to check.
pattern is the regular expression you want to match.
True.'Hello World' -match 'World'
'123-456' -match '\d{3}-\d{3}'
'apple' -match '^a'
'test@example.com' -match '\w+@\w+\.com'
This script looks for a phone number pattern in the text. If found, it prints the number.
$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.' }
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.
-match checks if text fits a pattern.
Use $matches to get the matched part.
Regular expressions help find complex text patterns easily.
-match operator do in PowerShell?-match-match operator is used to test if a string matches a regular expression pattern.-replace, splitting uses -split, and uppercase conversion uses ToUpper(). These are different from -match.-match = pattern check [OK]$text contains the word 'hello' using -match?-match syntax$variable -match 'pattern' to test if the variable matches the pattern.$var -match 'pattern' to test matches [OK]$text = 'My phone number is 123-456-7890'
if ($text -match '\d{3}-\d{3}-\d{4}') {
$matches[0]
} else {
'No match'
}\d{3}-\d{3}-\d{4} matches a phone number format with three digits, a dash, three digits, a dash, and four digits.$matches[0] contains$matches[0] holds the matched substring, so it outputs '123-456-7890'.$text = 'Error code: 404'
if ($text -match '\d{3}') {
Write-Output $matches
}$lines. Which PowerShell snippet correctly uses -match and $matches to collect emails into $emails?-match and if it matches, collect the matched email from $matches[0].-match, and collects matched emails correctly. $emails = $lines -match '[\w.-]+@[\w.-]+\.\w+' tries to match the whole array at once, which doesn't work. $emails = $lines | Where-Object { $_ -contains '[\w.-]+@[\w.-]+\.\w+' } uses -contains which does not support regex. $emails = foreach ($line in $lines) { $line -match '[\w.-]+@[\w.-]+\.\w+' } runs -match but does not collect matched emails.Pass the test and this pattern moves unknown