Credit Card Number
Match 16-digit credit card numbers with optional spaces or hyphens between groups of 4.
Try it in RegexPro →Available in
JavaScript / ECMAScript code
const re = new RegExp("\\b(?:\\d{4}[\\s\\-]?){3}\\d{4}\\b", "g");
const input = "4111 1111 1111 1111";
const matches = [...input.matchAll(re)];
console.log(matches.map(m => m[0]));Uses `String.prototype.matchAll` for global iteration (Node 12+ / all modern browsers).
Python (re) code
import re
pattern = re.compile(r"\b(?:\d{4}[\s\-]?){3}\d{4}\b")
input_text = "4111 1111 1111 1111"
for m in pattern.finditer(input_text):
print(m.group(0))Stdlib `re` module — no third-party dependency. Works on Python 3.6+.
Go (RE2) code
package main
import (
"fmt"
"regexp"
)
func main() {
re := regexp.MustCompile(`\b(?:\d{4}[\s\-]?){3}\d{4}\b`)
input := `4111 1111 1111 1111`
for _, match := range re.FindAllString(input, -1) {
fmt.Println(match)
}
}Uses `regexp.MustCompile` (panics on bad patterns at startup) and `FindAllString` for all matches.
Pattern
\b(?:\d{4}[\s\-]?){3}\d{4}\b (flags: g)Raw source: \b(?:\d{4}[\s\-]?){3}\d{4}\b
How it works
Examples
Input
4111 1111 1111 1111Matches
4111 1111 1111 1111
Input
4111-1111-1111-1111Matches
4111-1111-1111-1111
Input
4111111111111111Matches
4111111111111111
Common use cases
- •PCI-DSS data discovery scans
- •Detecting card numbers in logs (for masking)
- •Payment form validation
- •Data loss prevention (DLP) tools
Related patterns
ISBN-10
ValidationMatch 10-digit ISBNs, allowing optional hyphens or spaces between groups.
ISBN-13
ValidationMatch 13-digit ISBNs starting with 978 or 979, with optional hyphens or spaces.
International Phone Number (Loose)
ValidationMatch international phone numbers in a variety of loose formats including country codes, area codes, and separators.
US Phone Number
ValidationMatch US phone numbers in common formats: (555) 867-5309, 555-867-5309, 5558675309.
Related concepts
Word Boundaries: \b and \B
Concept\b matches the position between a word character and a non-word character. It keeps your regex from matching 'cat' inside 'concatenate.'
How to Match Digits in Regex
How-toUse \d for any digit, [0-9] for ASCII digits only, or {n} to match a specific count of digits. Combine with anchors for whole-string validation.
How to Match a Specific Number of Characters
How-toUse {n} for exactly n, {n,} for n or more, {n,m} for between n and m. Apply to any single token — character, class, or group.