Regexdrill

Level 3: Real-world validation Exercise 43 of 88 Free

Card numbers in groups of four

A regex exercise from Regexdrill. Solve it with a pattern box with live highlighting in your browser, checked against hidden test strings, and it is checked the moment you submit.

The task

The whole line must match. Match 16 digits written as four groups of four. The groups are separated by single spaces, by single hyphens, or by nothing at all, and the separator must be the same throughout.

What this exercise teaches

([ -]?) captures a space, a hyphen or nothing, and each \1 demands that same text again, so mixed separators fail. This checks the shape only: whether a card number is valid takes the Luhn checksum, which a regex cannot compute.

A hint if you get stuck

Capture the first separator, which may be empty, in a group: ([ -]?). Then reuse it with \1 between the other groups.

Try it now, free, no account needed

Every exercise on Regexdrill is free to try. Open it on the practice page, solve it, and get instant feedback with a hint. The worked solution opens once you solve it or after two tries.

Open this exercise

More exercises in Real-world validation