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.

Exactly 6 hex characters (CSS color)

Try this
/^#[0-9a-fA-F]{6}$/

Input

#ff5733

Result

Match

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.

Password: 8 or more characters

Try this
/^.{8,}$/

Input

shortpw

Result

No match

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.

Username: 3 to 20 word characters

Try this
/^\w{3,20}$/

Input

ab

Result

No match (too short)

Same regex, valid length

Try this
/^\w{3,20}$/

Input

valid_user

Result

Match

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

All reference guidesOpen the RegexPro tester →