Level 2: Practical patterns · Lesson 11 of 30
Counts {n,m}
Curly braces let you say exactly how many times something repeats: {3} for exactly three, {2,4} for two to four, and {2,} for two or more.
The quantifiers *, + and ? are flexible, but sometimes you need an exact count. A postal code has five digits, a year has four, and a short code may have two or three letters. Curly braces give you that control. They go after the item they repeat, just like the other quantifiers.
{n} means exactly n times. \d{4} matches four digits in a row, so it finds 2024 and 1999. [A-Z]{2} matches exactly two capital letters. This is clearer and safer than writing \d\d\d\d by hand, especially for longer counts.
{n,m} means between n and m times, inclusive. [a-z]{2,3} matches two or three lowercase letters. Like the other quantifiers, it is greedy: on the word more it takes three letters, mor, because three is the most it is allowed. If you need whole words only, combine it with word boundaries: \b[a-z]{2,3}\b.
{n,} means at least n times, with no upper limit. hm{2,} matches hmm, hmmm and hmmmm, but not hm. In fact the familiar quantifiers are shortcuts: * is the same as {0,}, + is {1,}, and ? is {0,1}.
Counts need boundaries or anchors to be strict. \d{4} on 98765 happily matches the first four digits, 9876. If you want standalone four-digit numbers, write \b\d{4}\b. For validating a whole input, write ^\d{4}$. This is the most common bug with counted quantifiers.
The syntax is nearly universal. JavaScript, Python, PHP, Java, Go, C#, Rust and Ruby all support {n}, {n,m} and {n,}. Python and Ruby also accept {,m} to mean zero to m times, but JavaScript treats {,5} as literal text, so write {0,5} for portable patterns. Go's RE2 engine limits counts to at most 1000 repetitions.
Do not put spaces inside the braces. \d{2, 4} is not a valid range in most engines; in JavaScript it silently becomes literal text. Keep it compact as \d{2,4}, and you can use lazy versions like {2,4}? when you want the fewest repetitions.
Live tester
2 matches (JavaScript engine)
12 345 6789
Examples
Numbers
/\b\d{4}\b/gyear 2024 code 12 id 98765
Matches: “2024”
Only the standalone four-digit number matches; boundaries reject the slice of 98765.
Text
/\b\w{5}\b/gapple kiwi lemon grape
Matches: “apple”, “lemon”, “grape”
Exactly five word characters between boundaries picks out the five-letter words.
Codes
/[A-Z]{2}\d{2,4}/gAB12 CD3456 E7
Matches: “AB12”, “CD3456”
Two capital letters followed by two to four digits; E7 has only one letter and one digit.
Practice tasks
Your regex runs over the text with the global flag. It passes when it finds every required match and nothing that should be left out.
Task 1: Match standalone four-digit numbers.
7 2024 123 98765 1999
Task 2: Match whole lowercase words that are two or three letters long.
a an the more go
Task 3: Match h followed by at least two m letters.
hm hmm hmmm hmmmm