Regular expressions·a card number written in four blocks of four

a card number written in four blocks of four

Matches a card number written in four blocks of four. It is anchored at both ends, so the whole string has to match. There are no capture groups.

Pattern
/^\d{4}(?:[ -]?\d{4}){3}$/
Match scope
the whole string
Capture groups
0
What it catches in the first example
4111111111111111

Try it yourself

Type any text and the parts this expression catches are highlighted. It runs in your browser and is never sent anywhere.

4111111111111111

1 match

Examples that match

  • 4111111111111111
  • 4111 1111 1111 1111
  • 4111-1111-1111-1111

Examples that do not match

  • 4111 1111 1111
  • 41111111111111111

Other expressions in this group

How to read this

  • With ^ and $ around it, the whole string must match; without them the match can sit anywhere. Always anchor an expression you use for validation.
  • Round brackets ( ) capture what they wrap. When you only need grouping, write (?: ) so the numbering of later groups does not shift.
  • Every expression here is checked against its examples. Even so, "looks like an email" and "is a real inbox" remain different questions.
  • Nested open-ended repeats such as (a+)+ can blow up on certain inputs. Look for that shape before pasting someone else’s expression into your code.

Frequently asked questions

Q. What is the regex for a card number written in four blocks of four?

^\d{4}(?:[ -]?\d{4}){3}$.

Q. Which strings match?

Text like 4111111111111111 matches; text like 4111 1111 1111 does not.

Q. Does the whole string have to match?

Yes. It is wrapped in ^ and $, so nothing but a full match passes.

Q. How do I use what it caught?

There are no capture groups, so only the whole match (match[0]) comes back. Wrap the part you need in brackets to capture it.