Wednesday, December 11, 2019

Validating Credit Card Numbers - Hacker Rank Solution

You and Fredrick are good friends. Yesterday, Fredrick received  credit cards from ABCD Bank. He wants to verify whether his credit card numbers are valid or not. You happen to be great at regex so he is asking for your help!

Validating Credit Card Numbers - Hacker Rank Solution

This problem can be divided into two parts:

Part1 :
Check if credit card number size if exactly 16, all the characters are integers and - symbol may be present after every group of 4 digits
All the above checks can be validated using : r'^[456]\d{3}(-?)\d{4}\1\d{4}\1\d{4}$'

Part2:
Check is credit card number has 4 or more repeating consecutive digits
This check can be validated using : r'(\d)\1{3,}''

import re
for i in range(int(raw_input())):
    S = raw_input().strip()
    pre_match = re.search(r'^[456]\d{3}(-?)\d{4}\1\d{4}\1\d{4}$',S)
    if pre_match:
        processed_string = "".join(pre_match.group(0).split('-'))
        final_match = re.search(r'(\d)\1{3,}',processed_string)
        print 'Invalid' if final_match else 'Valid'
    else:
        print 'Invalid'

No comments:

Post a Comment

Powered by Blogger.