Suppose a pattern must match either “Mr” or “Mrs,” with or without a final period. `/Mrs?\.?/` does it: each `?` makes the immediately preceding element optional. A quantifier specifies how many consecutive times a character, character class, or parenthesized group may match. section 11.5.1
The common shorthand quantifiers express three useful ranges:
- `?` means zero or one. In `\d\d?`, the second digit is optional. section 11.5.1
- `*` means zero or more. In `/<\s*\/\s*poem\s*>/`, each `\s*` allows any amount of whitespace, including none. section 11.5.1
- `+` means one or more. `/\d+/` finds a run of digits; matching it against `"Digits-R-Us 2345"` returns `"2345"`. section 11.5.1
Braces give explicit counts: `\d{3}-\d{4}` requires three digits, a hyphen, and four digits; `\d{1,10}` allows one to ten digits; `\d{3,}` requires at least three. Parentheses let a quantifier repeat a whole subpattern rather than one character. section 11.5.2
Greedy versus non-greedy
Given `string = "abc!def!ghi!"`, `/.+!/.match(string)[0]` returns `"abc!def!ghi!"`: `+` takes as much as it can while still allowing `!` to match. Add `?` after the quantifier—`/.+?!/`—and the result is `"abc!"`. Here `?` changes how `+` repeats; it does not make the preceding character optional. section 11.5.2
Greedy does not mean unwilling to give characters back. Against `"Digits-R-Us 2345"`, `(\d+)(5)` captures `"234"` and `"5"`: the engine backtracks so the final `5` in the pattern can match. Group placement also affects captures. `([A-Z]){5}` matches `"BLACK"` but captures only `"K"`; `([A-Z]{5})` captures `"BLACK"`. section 11.5.2
Use quantifiers to control repetition, then use anchors when the match must occur at a particular position. Without such a constraint, `/Mrs?\.?/` can also find a title within a longer string. section 11.5.1 section 11.5


