Quantifiers: star, plus and question

Beginner · 15 min

*, + and ? say how many times the thing before them may repeat: zero or more, one or more, zero or one. See the zero-width match trap and the grep differences.

Before thisCharacter classesShorthand classes

Wendi Jollymore · 39 min · from 2:31

Quantifiers: star, plus and question

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by Wendi JollymoreReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • * means zero or more, + means one or more and ? means zero or one. Each applies only to the single item right before it: a character, a class or a group.
  • ab+ repeats only the b, so it matches abbb. (?:ab)+ repeats the pair and matches ababab.
  • * can match nothing, so /\d*/.test('abc') is true. Use + when you need at least one, and anchor patterns that must consume the whole input.
  • ? makes a part optional: colou?r matches color and colour, and https?:// matches both schemes.
  • A quantifier with nothing to repeat is an error: /*a/ fails with 'Nothing to repeat'. In grep's basic syntax a leading * is a literal and + and ? need a backslash.

How many of these?

So far every piece of a pattern has matched exactly once: a literal once, a class once. But text repeats itself. A number has one or more digits. A word has several letters. A URL might say http or https. You need a way to say how many times a piece may occur, and three short symbols do the common cases.

  • * means zero or more.
  • + means one or more.
  • ? means zero or one, which is to say “optional”.

Each one attaches to whatever sits immediately before it. That can be a single character, a class or a group (parentheses are the next group of lessons, but you’ve met (?:...) already).

"tel 555 0142 ext 7".match(/\d+/g)       // [ '555', '0142', '7' ]
"ac abc abbc".match(/ab*c/g)             // [ 'ac', 'abc', 'abbc' ]
"x-123-abc".match(/[0-9]+/g)             // [ '123' ]

In the middle line ab*c accepted ac (no b), abc and abbc. The * allowed zero of them.

Only the thing before

A quantifier doesn’t reach back across a whole word. It applies to one item, and that matters:

"ababab abbb".match(/ab+/g)        // [ 'ab', 'ab', 'ab', 'abbb' ]
"ababab abbb".match(/(?:ab)+/g)    // [ 'ababab', 'ab' ]

ab+ is “an a, then one or more b”. It matched ab three separate times in the first word, and abbb in the second. (?:ab)+ is “the pair ab, one or more times”, so the first word matched whole. If you want the pair, wrap the pair.

Optional means zero or one

? is the quantifier behind most “this part may be absent” patterns:

"color colour colouur".match(/colou?r/g)                  // [ 'color', 'colour' ]
["http://a.org","https://a.org","ftp://a.org"].map(u => /^https?:\/\//.test(u))
// [ true, true, false ]
["5550142","555-0142","555--0142"].map(s => /^\d{3}-?\d{4}$/.test(s))
// [ true, true, false ]

The u in colour is optional, colouur has two, so it did not match. The s of https is optional. And a phone number may have one dash or none, but not two. Optional groups work the same way: /^\d (cat)s?$/ accepted 1 cat and 2 cats and rejected 3 cat s.

The zero-width trap

The danger sits in *. Because it allows zero repetitions, it can match nothing, and an empty match is still a match:

/\d*/.test("abc")          // true
/^\d+$/.test("abc")        // false
/^\d*$/.test("")           // true
/^\d+$/.test("")           // false

The first line says “abc” contains a run of zero or more digits, which is true because the empty run is always there. If you want at least one, use +. This also shows in match with the g flag, which reports the empty matches too:

"baaac".match(/a*/g)             // [ '', 'aaa', '', '' ]
"abc".replace(/x*/g, "-")        // "-a-b-c-"

x* matched the empty string at every position, so a dash went in before each character and at the end. The same text through four tools gave a small surprise. "baaac".replace(/a*/g, "X") in Node, Python 3.9 and Perl all printed XbXXcX. BSD sed -E 's/a*/X/g' printed XbXcX, one fewer X (I did not look into why). Don’t depend on the count of empty matches.

Errors and the tool differences

A quantifier needs something to repeat. Each of these fails in JavaScript with Nothing to repeat: *a, a**, +, a+* and ?. Python 3.9 says nothing to repeat at position 0 for *a. Combining a quantifier with a second ?, as in a+?, is allowed and means something different, the lazy form. The greedy and lazy lesson covers it.

In grep’s basic syntax the rules shift again. A leading * is a literal, and + and ? are literal until you escape them:

$ echo '*a' | /usr/bin/grep -o '*a'            *a
$ echo 'aaa' | /usr/bin/grep -o 'a\+'          aaa
$ echo 'color colour' | /usr/bin/grep -o 'colou\?r'    color, colour
$ echo 'color colour' | /usr/bin/grep -oE 'colou?r'    color, colour
$ echo 'color' | /usr/bin/grep -o 'colou?r'    (no output, exit 1)

So colou\?r in basic syntax and colou?r with -E are the same pattern. BSD grep accepted \+ and \? in basic mode, which is a GNU extension to POSIX. See the flavors lesson.

About the video

The embed is a clip of Wendi Jollymore’s “Basic Regular Expressions 3 - Quantifiers and Anchors”, published on 18 April 2022 and 38 minutes 52 seconds long. The clip runs from 2:31 to 17:12, covering her chapters “Intro to Quantifiers”, “One or More +”, “Zero or More *”, “Optional ?” and an exercise. The next chapter, {N} quantifiers, belongs to the next lesson and is left out. Her description names regexr as the tester. I couldn’t read a transcript, so I can’t say whether she warns about the zero-width trap or the tool differences, which are from my own runs. English per its title and description.

What I did not run

GNU grep, regex101, and the behaviour of empty matches in Ruby, Java and Go.

Next

*, + and ? count loosely. When you need an exact count or a range, there is Counted repetition.

Check yourself

  1. 01What is the difference between ab+ and (ab)+?

    The + binds to the single item before it. In ab+ that is b, so it matches a followed by one or more b. In (ab)+ the group repeats, so it matches ab, abab, ababab and so on.

  2. 02Why does /\d*/.test('abc') return true?

    \d* is allowed to match zero digits, and the engine can do that at position 0. Use /\d+/ to require at least one digit.

  3. 03What does 'abc'.replace(/x*/g, '-') return and why?

    '-a-b-c-'. x* matches the empty string at every position, so a dash goes before each character and at the end.

  4. 04How do you write 'color or colour' as one pattern?

    /colou?r/. The ? makes the u optional, so the pattern matches both spellings.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark