Level 1: Foundations · Lesson 9 of 30
Groups ( )
Parentheses group several characters into one unit so you can repeat them or make them optional, and they capture the matched text for later use.
Parentheses create a group. Everything inside a group is treated as one unit. This matters most with quantifiers, which normally apply only to the single item before them. ha+ matches ha, haa and haaa, but (ha)+ matches ha, haha and hahaha, because the plus now repeats the whole pair.
Groups can make a chunk optional. Mon(day)? matches both Mon and Monday. Without the group, Monday? would only make the final y optional. Thinking about which piece a quantifier applies to is the key skill in this lesson.
Groups also capture. When a pattern matches, the engine remembers the text matched by each group, numbered from left to right by their opening parenthesis. In (\d+)-(\d+) applied to 10-20, group 1 holds 10 and group 2 holds 20. In JavaScript you read them from the match array as m[1] and m[2]; Python uses m.group(1), PHP fills $matches[1], and Java and Go have similar methods.
Captured groups are useful in replacements too. In JavaScript you can write $1 in the replacement string to insert group 1, so replacing (\w+) (\w+) with $2 $1 swaps two words. Python's re.sub uses \1 or \g<1> for the same job. The replacement lesson later covers this in detail.
Sometimes you want grouping without capturing. Write (?:...) for a non-capturing group. (?:ab)+ repeats ab just like (ab)+, but it does not store the text. Non-capturing groups keep group numbers tidy and are slightly cheaper. They are supported in JavaScript, Python, PHP, Java, Go, C#, Rust and Ruby.
Important for practice tasks: a group does not change the full match. The task checker on this site looks at the whole matched text, also called group 0. Captured groups are extra information on top. So (\d+)-(\d+) still reports the full match 10-20.
Groups can be nested, as in ((ab)+c), and combined with every other feature you have learned. Keep them as simple as possible, though. If a pattern needs many nested groups, consider splitting the problem into smaller steps in your code.
Live tester
3 matches (JavaScript engine)
ha haha hahaha
Examples
Numbers
/(\d+)-(\d+)/grange 10-20 and 5-9
Matches: “10-20”, “5-9”
Each match captures the start and end numbers in groups 1 and 2.
Text
/(re)+do/gredo rerere do rererdo
Matches: “redo”
The group repeats the pair re, so redo matches while broken sequences do not.
Codes
/([A-Z]+)-(\d+)/gAB-12 XYZ-7
Matches: “AB-12”, “XYZ-7”
The letter prefix and the number are captured separately for later use.
Practice tasks
Your regex runs over the text with the global flag. It passes when it finds every required match and nothing that should be left out.
Task 1: Match laughter made of one or more ha pairs.
ha haha hahaha hah
Task 2: Match Mon and Monday, but not the partial word Mond.
Mon Monday Mond Tuesday
Task 3: Match ab repeated at least twice in a row.
abab ab abba ababab