How-to
How to Match a Specific Number of Characters
Use {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.
Exact count with {n}
\d{4} matches exactly 4 digits — useful for years, PIN codes, and fixed-length identifiers. [A-Z]{2} matches exactly two uppercase letters. Works with any preceding token.
At least N with {n,}
No upper bound. Useful when you know a minimum length but can't (or shouldn't) cap it. Names, descriptions, or anything where the legitimate upper bound is the storage constraint, not the syntax.
Range with {n,m}
Bounded both ways. No space inside the braces — {2, 4} is a literal match for '{2, 4}', not a range. Common for username length rules, phone-number digit runs, and input fields with both min and max constraints.
Applying counts to groups
(\d{4}-){3}\d{4} matches a credit-card-like shape: three groups of '4 digits + hyphen' followed by a final 4 digits. The {3} applies to the whole (\d{4}-) group. Without the parens, {3} would only apply to the preceding token.
Related patterns
Credit Card Number
Match 16-digit credit card numbers with optional spaces or hyphens between groups of 4.
/\b(?:\d{4}[\s\-]?){3}\d{4}\b/gUS ZIP Code
Match US ZIP codes in 5-digit (12345) and ZIP+4 (12345-6789) formats.
/\b\d{5}(?:[\-\s]\d{4})?\b/gUUID (v1–v5)
Match RFC 4122 UUIDs (versions 1–5) in the standard 8-4-4-4-12 hex format.
/[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a…/giIPv4 Address
Match valid IPv4 addresses with each octet constrained to 0–255.
/(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)…/g