Lessons · Regex · search or match: where it starts looking
Where the engine starts looking
match anchors the pattern at the very start of the string; search scans forward until it finds one.
Hone is a place to practise programming. This is one of its lessons, written out in full and free to read without an account.
What it is for
It is the commonest reason a pattern that is right looks broken. The digits are there; they are just not first.
How to think about it
Ask what the question really is. 'Does it contain' is search. 'Does it begin with' is match. 'Is it exactly' is fullmatch. Reaching for match out of habit blames the pattern for the wrong call.
Worked example
re.match(r'\d+', 'abc 123')Nothing, because the string does not BEGIN with digits.
re.search(r'\d+', 'abc 123').group()search scanned forward and found them.
re.match(r'\d+', '12abc').group()match is happy here, and says nothing about the abc.
Your turn
Find the digits anywhere in the string.
re.(r'\d+', 'abc 123').group()
Test a pattern against real text
The trap
A successful match is not proof the whole value is what you wanted. It stops the moment the pattern is satisfied.
Practise search or match: where it starts looking on HoneA question on it now, a coding challenge where there is one, and it is remembered for review. Free, no email needed.