Can a regex match valid card numbers?

3 subset 2 9/7/2025, 8:45:41 AM abstractnonsense.xyz ↗

Comments (2)

subset · 1d ago
This was a problem that was obsessing me for a couple sleepless nights...

Ordinarily, when you look up "regex for card numbers" you get a list of card provider prefixes and length constraints, but this doesn't do any validation on the check digit (calculated using the Luhn algorithm)!

Spoiler: Regex's _can_ recognise the set of valid card numbers, but the resulting regex would be exponential in the number of states for the minimal DFA (as far as I can reason).

bediger4000 · 10h ago
This is excellent!

I worked at a Visa Level 1 merchant 2003-2006. We had Luhn checks scattered throughout the code, which led to some delightful bugs.

From the post: "walk over the digits from right-to-left, alternating between adding the digit and adding the “Luhn double” of the digit to a rolling sum."

That algorithm is good to see, and I'm glad that everyone has come around to that method, but in 2003, that was absolutely not how folks did it. MasterCard and Discover numbers were known to be 16 digits. Visas where 16 digits, and it was rumored that some accounts had 12 digit numbers. Never saw one in the wild. Of course American Express is from Mars and has 13 digit numbers, and a 4 digit CVV.

The several Luhn-checks in the code always looked at length of the card number and based on that, started with a "luhn double" or with a regular number. The Luhn check documentation at the time did it that way in their examples. That made for some super clunky code resembling Fortran, no matter what language you wrote it in.