Hone

Lessons · Regex · {2,4}: between two counts

Exactly, at least, between

{n} means exactly n, {n,} at least n, {n,m} between n and m inclusive. \d{3} is three digits; \d{2,4} is two to four.

Hone is a place to practise programming. This is one of its lessons, written out in full and free to read without an account.

What it is for

Postcodes, card numbers, years, hex colours: fixed and bounded lengths are what makes a pattern precise instead of 'some digits'.

How to think about it

Write the count you mean. If a value can be 2 to 4 digits, say {2,4} and anchor it, or a longer run will still match its first four.

Worked example

pattern: \d{3}
Exactly three digits.
text: 12 345 6789
Matches 345, then 678: the run of four yields one match of three.
pattern: ^\d{2,4}$
Two to four digits, and nothing else.
text: 123
Match.
text: 12345
No match: five is too many.

Your turn

A word of at least five letters.

[a-z]{}

The trap

a{2,4} is greedy: on aaaaa it takes four, then the remaining a matches on its own only if the pattern allows it. Anchor or bound it when the length matters.

Practise {2,4}: between two counts on HoneA question on it now, a coding challenge where there is one, and it is remembered for review. Free, no email needed.