Skip to content

Instantly share code, notes, and snippets.

@JimDennis
Created June 23, 2019 01:36
Show Gist options
  • Save JimDennis/c3586a91c194e014e625079e53c73d02 to your computer and use it in GitHub Desktop.
Save JimDennis/c3586a91c194e014e625079e53c73d02 to your computer and use it in GitHub Desktop.
Python Regular Expression: Validate American Style Comma Separated Integers
# Regular expression to validate if a string is a valid integer with
# commas separating thousands, millions, billions and so on
import re
# start with some test cases:
good_tests = ['1', '12', '123', '1,234', '12,345', '123,456',
'1,234,567', '12,345,678', '123,456,789']
fail_tests = ['1234', '1,2345', '12,34', '1,2', '1,23', '1.2', '1,234.5']
# implement a test harness
class TestPattern:
def __init__(self, good, bad):
self.good = good
self.bad = bad
def __call__(self, pattern):
return all((pattern.match(g) for g in self.good)) and not any((pattern.match(b) for b in self.bad))
# instantiate a tester with our test cases:
test = TestPattern(good_tests, fail_tests)
# here's a pattern:
pattern = re.compile(r'^\d{1,3}(,\d{3})*$')
# use our tester:
test(pattern)
# return True
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment