Validating Credit Card Numbers

  • + 0 comments

    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")