Quantifiers
Control how many times a pattern element must appear.· 7 min
Concept
Quantifiers specify how many times the preceding element (character, class, or group) must match:
- ? — 0 or 1 time (optional)
- + — 1 or more times
- * — 0 or more times
- {n} — exactly n times
- {n,m} — between n and m times (inclusive)
- {n,} — n or more times
By default, quantifiers are **greedy**: they match as much as possible. Add ? after to make them **lazy** (match as little as possible): +?, *?, {n,m}?.
Example: .+ matches one or more of any character. \d{4} matches exactly four digits.
/colou?r/g? makes the 'u' optional — matches both 'color' and 'colour'
/\d+/gMatches one or more consecutive digits
/\d{3}-\d{4}/gMatches a phone number format: exactly 3 digits, hyphen, exactly 4 digits
Exercise
Write a pattern that matches one or more consecutive digits anywhere in a string.
Your pattern: