Introduction
Regex quantifiers and anchors help you find patterns in text by specifying how many times something appears and where it appears.
$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
'abc' -match '^a.*c$'
'hello123' -match '\d+'
'aaa' -match 'a{2,3}'
'test' -match '^t.*t$'
$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" } }
+ mean when used like a+?a+ matches strings with at least one 'a' repeated consecutively.^test$ ensures the string starts and ends exactly with 'test' and nothing else.$text = 'aaaab';
$text -match '^a{3,5}b$'
$string = 'hello123';
if ($string -match '^hello\d+$') { 'Match' } else { 'No Match' }
^hello\d+$ correctly matches strings starting with 'hello' followed by one or more digits until the end.^cats*$ means start with 'cat', then zero or more 's', end of string -- matches requirement.^cat+s$ means start with 'ca' then one or more 't's, then 's' at end -- incorrect.^cat?s$ means start with 'ca', zero or one 't', then 's' at end -- incorrect.cats*$ no start anchor, so can match anywhere -- incorrect.Pass the test and this pattern moves unknown