Grouping with parentheses
Parentheses turn several characters into one unit, so a quantifier or a | can apply to the whole group. See ab+ vs (ab)+ and ^cat|dog$ vs ^(cat|dog)$ run.
Quantifiers: star, plus and questionAlternationHow a pattern is read: precedence and grouping
Grouping with parentheses
The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.
Not started
What you'll learn
- A quantifier binds to the single thing just before it. In ab+ the + repeats the b, so ab+ matches abbb but only the first ab in ababab.
- Wrapping pieces in ( ) makes them one unit. (ab)+ repeats the whole pair, so it matches ababab in one go.
- The | operator splits the entire pattern unless you fence it in. ^cat|dog$ means starts with cat OR ends with dog, while ^(cat|dog)$ means the whole string is cat or dog.
- A group can take a quantifier of its own: (\d{3}-){2} repeats three digits and a dash twice, and (www\.)? makes the whole www. prefix optional.
- In most flavours a plain ( ) also captures what it matched. That is a side effect, and the next lessons deal with it. In grep and sed basic syntax you write the parentheses as \( and \).
The problem: operators only see one thing
Say you want to match ababab. You know + means “one or more”, so you write ab+. It matches, but not the way you meant. On ababab it matches just ab. On abbb it matches all four characters. The pattern didn’t repeat ab. It repeated b.
That is how every quantifier works. *, +, ? and {n} bind to the one thing immediately to their left: a literal character, a ., a [...] class, or an escape like \d. A pattern is read piece by piece, and the piece in front of a quantifier is a single atom. To repeat a longer chunk you need a way to say “treat these several characters as one atom”. That is what parentheses do.
Parentheses make one unit
I ran these in Node 26 against ababab and abbb:
/ab+/ on "ababab" -> "ab"
/(ab)+/ on "ababab" -> "ababab"
/ab+/ on "abbb" -> "abbb"
(ab)+ says “one or more copies of the pair ab”. Think of it as a stamp. The stamp is ab, and the + says how many times you press it.
The same trick works with counts and with ?. A US-style phone number like 555-867-5309 is two repeats of “three digits and a dash”, then four digits:
/^(\d{3}-){2}\d{4}$/ on "555-867-5309" -> "555-867-5309"
/^(\d{3}-){2}\d{4}$/ on "555-867-530" -> no match
And an optional prefix is a group with a ? on it. ^https?:\/\/(www\.)?example\.com$ matched both https://www.example.com and http://example.com. Without the parentheses, the ? could only make the final . optional.
Parentheses fence in an alternation
The other job is limiting how far a | reaches. The alternation lesson made the point that | has the lowest precedence of everything in a pattern. It cuts the pattern in two at the pipe. So ^cat|dog$ is not “the string is cat or dog”. It is “starts with cat, or ends with dog”:
/^cat|dog$/ on "catalog" -> "cat"
/^(cat|dog)$/ on "catalog" -> no match
/^cat|dog$/ on "hotdog" -> "dog"
/^(cat|dog)$/ on "hotdog" -> no match
/^cat|dog$/ on "cat dog" -> "cat"
/^(cat|dog)$/ on "cat dog" -> no match
The unparenthesised version accepts catalog, hotdog and cat dog. The parenthesised one accepts only cat or dog and nothing else. This is the single most common alternation bug, and it hides well because the pattern still works on the examples you thought of.
Groups also let alternatives share a prefix instead of repeating it. gr(a|e)y matched gray and grey and rejected groy. For one-character choices a class does the same job, and gr[ae]y is shorter. A group wins once the choices are longer than one character, like (Mon|Tues|Wednes)day.
The side effect you didn’t ask for
In most flavours a plain pair of parentheses does a second job: it remembers what it matched. /(ab)+/.exec('ababab') returned ["ababab","ab"]. The second item is the group’s capture, and it holds only the last repetition. Often you want the grouping and not the memory. The next lesson shows how to read captures, and non-capturing groups shows how to turn the memory off.
Dialects: where parentheses are literal
In JavaScript, Python, Perl, PCRE (pcre2grep -o '(ab)+' printed ababab) and POSIX extended syntax, ( and ) are operators. In POSIX basic syntax (what plain grep and sed use) they are ordinary characters, and the operators are spelled \( and \). I checked with macOS BSD tools:
$ printf 'ababab\n' | /usr/bin/grep -o '(ab)+'; echo "exit=$?"
exit=1
$ echo 'foo(ab)+bar' | /usr/bin/grep -o '(ab)+'
(ab)+
$ printf 'ababab\n' | /usr/bin/grep -oE '(ab)+'
ababab
$ echo 'ababab-x' | /usr/bin/sed 's/\(ab\)*/<&>/'
<ababab>-x
$ echo 'ababab-x' | /usr/bin/sed -E 's/(ab)+/<&>/'
<ababab>-x
In basic mode (ab)+ searched for the literal text, found it in foo(ab)+bar, and found nothing in ababab. Python agreed with JavaScript: re.search(r'^(cat|dog)$', 'dog') matched. The grep lesson explains basic versus extended in more detail.
About the video
The embedded clip is DevTips’ “What do () parenthesis and | pipe mean in RegExp? #2 REGEX ULTRA BASICS”, published 22 June 2018 and 26 minutes 2 seconds long. It is JavaScript, using VS Code with a live-evaluation plugin. I set the clip to run from 3:20 to 14:04, which covers the chapters titled “Capture Groups” and “alternation” in its chapter list. The description says it shows capture groups, non-capture groups and alternation. I couldn’t read a transcript, so I can’t say how it explains quantifiers on groups or the precedence of |. If it only touches those briefly, the sections above are the fuller version. English per its title and description.
What I did not run
GNU grep and GNU sed, where \+ and \| work in basic mode, and regex101’s explanation panel.
Next
Parentheses also remember. Capturing groups and numbering shows how to read what they captured.
Check yourself
What does /ab+/ match in the string ababab, and what would you change to match the whole string?
It matches only the first ab, because the + applies to the b alone. Group the pair and anchor it: /^(ab)+$/ matches ababab.
Why does /^cat|dog$/ match the string catalog?
The | has the lowest precedence, so the pattern is really ^cat OR dog$. The first branch, ^cat, matches the start of catalog. Writing /^(cat|dog)$/ confines the choice to the middle.
How would you match an optional www. prefix in a hostname?
Group the prefix and add a question mark: (www\.)?. The ? then applies to all four characters as one unit, and the dot is escaped so it only matches a real dot.
You run grep -o '(ab)+' on a file and nothing matches. What is going on?
Plain grep uses basic syntax, where ( and + are ordinary characters, so it searches for the literal text (ab)+. Use grep -E for extended syntax, or write \(ab\)\+ if you must stay in basic mode.
Notes
Notes are saved to your account.
Everything else on this page works without one — progress and bookmarks keep themselves in this browser and come with you when you sign in. Notes are the one thing worth not trusting to a browser you might clear.
Your notes could not be loaded.