Skip to main content
Regexflux
Lesson 5 of 120 completed

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'

favorite color
favourite colour
colr
colour scheme
/\d+/g

Matches one or more consecutive digits

order 123
12345 total
1 item
no digits
/\d{3}-\d{4}/g

Matches a phone number format: exactly 3 digits, hyphen, exactly 4 digits

call 555-1234
phone: 800-5678
12-3456
5555-1234

Exercise

Write a pattern that matches one or more consecutive digits anywhere in a string.

Your pattern:

Must match

order 123
12345 total
1 item
abc1def

Must not match

no digits
abc def
hello world