0
0
PowerShellscripting~5 mins

Regex quantifiers and anchors in PowerShell

Choose your learning style9 modes available
Introduction
Regex quantifiers and anchors help you find patterns in text by specifying how many times something appears and where it appears.
Checking if a phone number has exactly 10 digits.
Finding words that start with a capital letter.
Validating if an email address ends with '.com'.
Extracting repeated characters in a string.
Ensuring a password contains at least one number.
Syntax
PowerShell
$pattern = '^abc{2,4}\d+$'
# ^ is start anchor
# c{2,4} means 'c' repeats 2 to 4 times
# \d+ means one or more digits
# $ is end anchor
Anchors (^ and $) match positions, not characters.
Quantifiers like *, +, ?, {n,m} control how many times a part repeats.
Examples
Matches strings starting with 'a' and ending with 'c', with anything in between.
PowerShell
'abc' -match '^a.*c$'
Matches if the string contains one or more digits anywhere.
PowerShell
'hello123' -match '\d+'
Matches if 'a' repeats 2 to 3 times consecutively.
PowerShell
'aaa' -match 'a{2,3}'
Matches strings starting and ending with 't'.
PowerShell
'test' -match '^t.*t$'
Sample Program
This script checks each string to see if it starts with 'ab', followed by 2 or 3 'c's, then ends with one or more digits.
PowerShell
$texts = @('abc123', 'abcc123', 'abccc1234', 'ab123')
foreach ($text in $texts) {
    if ($text -match '^abc{2,3}\d+$') {
        Write-Output "$text matches the pattern"
    } else {
        Write-Output "$text does NOT match the pattern"
    }
}
OutputSuccess
Important Notes
In PowerShell, use single quotes for regex patterns to avoid unwanted expansions.
Remember to escape special characters like \d for digits.
Anchors help ensure the pattern matches the whole string or specific positions.
Summary
Regex quantifiers control how many times a character or group repeats.
Anchors (^ and $) specify the start and end positions in the text.
Together, they help you find exact patterns in strings.