Lessons · Regex · fullmatch: all of it or nothing
All of it, or nothing
fullmatch requires the pattern to account for every character in the string.
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
Validation. 'Is this a postcode' and 'does this contain a postcode' are different questions, and only one of them keeps junk out of your database.
How to think about it
If the field must hold this and nothing else, fullmatch says so in one word. The alternative is anchors at both ends, which is the same statement with more punctuation.
Worked example
re.fullmatch(r'\d+', '123').group()The whole string is digits.
re.fullmatch(r'\d+', '123abc')Not all of it, so no match at all.
bool(re.search(r'\d+', '123abc'))search is perfectly happy, which is the danger.
Your turn
Say whether each of '123' and '123abc' is ENTIRELY digits.
[bool(re.(r'\d+', s)) for s in ('123', '123abc')]Test a pattern against real text
The trap
fullmatch is not lenient about a trailing newline. A value read from a file usually still has one on it.
Practise fullmatch: all of it or nothing on HoneA question on it now, a coding challenge where there is one, and it is remembered for review. Free, no email needed.