We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
Validating Credit Card Numbers
Validating Credit Card Numbers
Sort by
recency
|
483 Discussions
|
Please Login in order to post a comment
Love this challenge ! It was very fast for me to check the 5 first conditions in regex, but so complex to check the "Not 4 or more consecutive repeated digits" condition.
For those who come after, I think that a good tip is to create 2 regex patterns. Instead of doing 1 big pattern.
In my logic, I check all conditions except the first one. Because if already one of them is not valid, I can print "Invalid".
But if all conditions are valid, then I check the consecutive repeated digit condition.
For that, I firstly remove "-" if necessary, because it's obviously most complex if not.
Then I use the regex pattern "([0-9])\1{3,}".
I didn't know the "back reference" in regex (\1, \2 etc...).
\1 means : "re-use the last group"
So ([0-9])\1 means : I capture a digit. And I want this exact same digit after.
Obviously, by adding {3,} we want that this logic is applied 3 times or more.
And if this condition is True, it's Invalid, because we don't want to have 4 consecutives repeated digits.
Note: Be careful to use re.search() and not re.match() for this pattern. Because re.match() only search at the start, whereas re.search() search everywhere in the string.
Here my code :
Here is HackerRank Validating Credit Card Numbers in Python solution - https://programmingoneonone.com/hackerrank-validating-credit-card-numbers-solution-in-python.html
import re regex_format = r'^(?:\d{16}|\d{4}(?:-\d{4}){3})$'
regex_no_consecutive = r'(\d)(?:-?\1){3}'
card = input().strip()
if not re.match(regex_format, card): print("Invalid") else: # Remove hyphens so we can sum digits digits_only = card.replace('-', '') # 2) Check for any digit repeated 4+ times consecutively if re.search(regex_no_consecutive, card): print("Invalid") else: # 3) Sum of digits > 16? total = sum(int(d) for d in digits_only) print("Valid" if total > 16 else "Invalid")