Can a Regex Match Valid Card Numbers?
Posted4 months agoActive4 months ago
abstractnonsense.xyzTechstory
calmpositive
Debate
20/100
RegexLuhn AlgorithmCard Validation
Key topics
Regex
Luhn Algorithm
Card Validation
Discussion about using regex to validate card numbers and the Luhn algorithm.
Snapshot generated from the HN discussion
Discussion Activity
Light discussionFirst comment
15m
Peak period
1
0-12h
Avg / period
1
Key moments
- 01Story posted
Sep 7, 2025 at 4:45 AM EDT
4 months ago
Step 01 - 02First comment
Sep 7, 2025 at 5:00 AM EDT
15m after posting
Step 02 - 03Peak activity
1 comments in 0-12h
Hottest window of the conversation
Step 03 - 04Latest activity
Sep 13, 2025 at 5:52 AM EDT
4 months ago
Step 04
Generating AI Summary...
Analyzing up to 500 comments to identify key contributors and discussion patterns
ID: 45156514Type: storyLast synced: 11/17/2025, 6:02:46 PM
Want the full context?
Jump to the original sources
Read the primary article or dive into the live Hacker News thread when you're ready.
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.
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).