Skip to content

Instantly share code, notes, and snippets.

@carlwiedemann
Created November 24, 2019 02:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save carlwiedemann/a7acfed80dc628380f1b70ca22b6df63 to your computer and use it in GitHub Desktop.
Save carlwiedemann/a7acfed80dc628380f1b70ca22b6df63 to your computer and use it in GitHub Desktop.
pin.py
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"))
@carlwiedemann
Copy link
Author

Running:

$ python3 foo.py
Three digits:
False
Four digits:
True
Five digits:
False
Six digits:
True
Six digits with newline:
False
Six digits with newline, then digit:
False

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment