Created
November 24, 2019 02:44
-
-
Save carlwiedemann/a7acfed80dc628380f1b70ca22b6df63 to your computer and use it in GitHub Desktop.
pin.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import re | |
def does_pin_match(pin): | |
# FROM https://docs.python.org/3/library/re.html | |
# Matches the end of the string or just before the newline at the end of the | |
# string, and in MULTILINE mode also matches before a newline. foo matches | |
# both ‘foo’ and ‘foobar’, while the regular expression foo$ matches only | |
# ‘foo’. More interestingly, searching for foo.$ in 'foo1\nfoo2\n' matches | |
# ‘foo2’ normally, but ‘foo1’ in MULTILINE mode; searching for a single $ in | |
# 'foo\n' will find two (empty) matches: one just before the newline, and one | |
# at the end of the string. | |
# | |
# So, we can't use `^` and `$`, because `$` does not catch trailing newline. | |
# "123456\n" will match this: | |
# pattern = re.compile(r'^[0-9]{4}$|^[0-9]{6}$') | |
# | |
# Instead, we use `\A` and `\Z`. | |
pattern = re.compile(r'\A[0-9]{4}\Z|\A[0-9]{6}\Z') | |
return bool(pattern.match(pin)) | |
print("Three digits:") | |
print(does_pin_match('123')) | |
print("Four digits:") | |
print(does_pin_match('1234')) | |
print("Five digits:") | |
print(does_pin_match('12345')) | |
print("Six digits:") | |
print(does_pin_match('123456')) | |
print("Six digits with newline:") | |
print(does_pin_match("123456\n")) | |
print("Six digits with newline, then digit:") | |
print(does_pin_match("123456\n1")) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Running: