Lessons · Regex · + * ? quantifiers
How many times
A quantifier says how many of the thing before it: ? is 0 or 1, * is 0 or more, + is 1 or more, {n} exactly n, {n,m} between.
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
Almost nothing in real text is a fixed length. Postcodes, prices, names, ids: quantifiers are what let one pattern cover them all.
How to think about it
Which character, and how many of it? Describe one character first (a digit, a letter, a class), then attach the count. Ask whether zero is allowed; that is the difference between * and +.
Worked example
pattern: colou?ru is optional: 0 or 1 of it.
text: color and colourBoth spellings match.
pattern: ^\d{2,3}$Two or three digits, whole string.text: 42Match. 4 alone would not; 4242 would not.
Your turn
One or more letters.
[a-z]
Test a pattern against real text
The trap
* matches nothing at all, so a* matches the empty string in any text. When you mean 'some', use +.
Practise + * ? quantifiers on HoneA question on it now, a coding challenge where there is one, and it is remembered for review. Free, no email needed.