Bài học theo mô-đun (1/4)
`*`, `+`, `?`
Quantifiers tell the engine how many times to repeat the element that
precedes them. The three basic quantifiers are *, +, ?.
| Quantifier | Meaning | Example | Matches |
|---|---|---|---|
* | zero or more times | ba* | b, ba, baa |
+ | one or more times | ba+ | ba, baa |
? | zero or one times | colou?r | color, colour |
They apply to the last atom: a single character (a+), a class
(\d+), a group ((ab)+, module 4).
Pattern: \d+
Sample: Codici 7, 12 e 314.
^ ^^ ^^^\d+ matches "one or more digits", it does not stop at the first one: a
maximal sequence of consecutive digits.
Deep dive into the optional quantifier
The question mark ? applies only to the single character immediately preceding it. To make an entire sequence of characters or words optional, you must enclose them in parentheses, for example (https)?.
Try it
Find every sequence of one or more consecutive lowercase 'a's in the text.
Hiển thị gợi ý
Use the + quantifier (one or more).
Giải pháp khả dụng sau 3 lần thử
Review exercise
Find every integer, with an optional minus sign (e.g. `42`, `-3`, `0`). Use `?` for the optional minus and `+` for the digits.
Hiển thị gợi ý
Prefix -? to the digit class, so the minus sign is either present or absent.
Giải pháp khả dụng sau 3 lần thử
Additional challenge
Find both `color` and `colour` in the text using the optional quantifier `?`.
Hiển thị gợi ý
Place the ? after the letter u to indicate it can appear zero or one times.
Giải pháp khả dụng sau 3 lần thử