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 exerciseMore exercises in Real-world validation
- US ZIP and ZIP+4Free
- US phone number formatsFree
- Dates YYYY-MM-DDFree
- 24-hour times HH:MMFree
- 12-hour times with AM or PMFree
- Simple email addressesFree
- Web addressesFree
- Hex colorsFree
- IPv4 addresses, 0 to 255Free
- URL slugsFree
- UsernamesFree
- SKU codesFree
- Currency amounts with commasFree
- Decimal numbersFree
- Semantic versionsFree
- MAC addressesFree
- UUIDsFree
- Percentages from 0 to 100Free
- ISO 8601 timestampsFree