1 hour ago · Tech · hide · 0 comments

Take this validation function: import re TRAIN_NUMBER_RE = re.compile(r"\d{6}") # six digits def is_valid_train_number(value: str) -> bool: return bool(TRAIN_NUMBER_RE.match(value)) It looks reasonable, and it works for the intended cases: >>> is_valid_train_number("345071") True >>> is_valid_train_number("ABC123") False But, woah, it also accepts garbage suffixes: >>> is_valid_train_number("345071-in-abbey-wood") True That is a bug, totally not what the author intended. re.Pattern.match() (and its module-level shortcut, re.match()) only anchors at the start of the string. It happily reports a match as soon as it finds 345071 at the beginning, regardless of what comes after. If you want to check that the entire string conforms to the pattern, you need fullmatch() instead: def is_valid_train_number(value: str) -> bool: return bool(TRAIN_NUMBER_RE.match(value)) …then you’ll see: >>> is_valid_train_number("345071-in-abbey-wood") False >>> is_valid_train_number("345071") True So, there’s…

No comments yet. Log in to reply on the Fediverse. Comments will appear here.