Non-capturing groups

Beginner · 6 min

Use (?:...) to group without capturing. See how it keeps numbering stable and stops split and Python findall from returning pieces you did not ask for.

Before thisGrouping with parenthesesCapturing groups and numbering

DevTips · 26 min · from 16:40

Non-capturing groups

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

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

What you'll learn

  • (?:...) groups exactly like (...) but does not save the match and does not use up a group number.
  • Adding a capturing group in the middle of a pattern renumbers every group after it. Non-capturing groups cannot break $2 or m[2] in code that you edited later.
  • JavaScript split puts capture-group text into the output array. Wrapping the separator in a capturing group changes the result, and (?:...) turns that off.
  • Python findall returns only the groups when the pattern has any: (https?|ftp)://\S+ returns the scheme, not the URL. Use (?:...) or no group to get whole matches back.
  • Reach for (?:...) whenever you group only to scope a quantifier or a |, and keep plain ( ) for the pieces you want to read afterwards.

Why you’d want parentheses that forget

The last lesson ended on a quiet cost of grouping: every ( ) makes a numbered slot. Most of the time you group a piece of pattern only so that a ? or a | applies to the whole thing. You don’t care about that group’s text. But the engine records it anyway and hands it to you, and it takes a number.

That has two real consequences. Numbers shift when you edit the pattern. And some functions change their output when groups are present. A non-capturing group, written (?:...), gives you the grouping and none of the bookkeeping. It’s a fence, not a box.

Numbers that don’t move

Here is a pattern that extracts the hour from Monday at 9:

/(Mon|Tues)day at (\d+)/.exec('Monday at 9')
-> ["Monday at 9","Mon","9"]
/(?:Mon|Tues)day at (\d+)/.exec('Monday at 9')
-> ["Monday at 9","9"]

With the plain group, the hour is m[2]. Change the first group to (?:...) and the hour is m[1]. That sounds minor until the pattern is used in a replace with $2, or in code that reads m[3] four screens away. I ran 'Monday at 9'.replace(/(Mon|Tues)day at (\d+)/, "$2 o'clock $1") and got 9 o'clock Mon. With a non-capturing first group, $1 is the number and $2 doesn’t exist. A rule that keeps numbers stable: capture only what you will read. Everything else is (?:...).

Fixed-structure patterns benefit most. An IPv4-shaped pattern repeats a group three times, and the repetition is pure structure:

/^(?:\d{1,3}\.){3}\d{1,3}$/.exec('192.168.0.1') -> ["192.168.0.1"]
/^(\d{1,3}\.){3}\d{1,3}$/.exec('192.168.0.1')   -> ["192.168.0.1","0."]

The second form hands you a capture holding 0., the last pass, which nobody asked for. (This shape only checks form. It would also accept 999.1.1.1, and a later lesson on validation covers that.)

When groups change a function’s output

Two standard functions treat captures specially.

split in JavaScript includes captured text in the result array:

'a1b22c'.split(/\d+/)    -> [ 'a', 'b', 'c' ]
'a1b22c'.split(/(\d+)/)  -> [ 'a', '1', 'b', '22', 'c' ]
'a1b22c'.split(/(?:\d+)/) -> [ 'a', 'b', 'c' ]

Sometimes that is a useful feature, since you keep the separators. If you didn’t want it, a stray ( ) quietly adds them. Python’s re.split does the same: re.split(r'(\d+)', 'a1b22c') gave ['a', '1', 'b', '22', 'c'].

findall in Python is the sharper trap. With no groups it returns the whole matches. With one group, it returns only that group’s text. With two or more, it returns tuples. Using see http://a.io and ftp://b.io:

re.findall(r'(https?|ftp)://\S+', s)         -> ['http', 'ftp']
re.findall(r'(?:https?|ftp)://\S+', s)       -> ['http://a.io', 'ftp://b.io']
re.findall(r'((?:https?|ftp))://(\S+)', s)   -> [('http', 'a.io'), ('ftp', 'b.io')]

The first pattern looks like a URL matcher and returns schemes, because the group took over. JavaScript’s matchAll doesn’t do this. It always gives you full match objects, and m[0] is the whole URL either way.

Which flavours have it

(?:...) is in JavaScript, Python, Perl and PCRE. pcre2grep -o '(?:Mon|Tues)day' printed Monday, and Perl printed the hour from the full pattern. POSIX extended syntax doesn’t define it, and my results were inconsistent on macOS:

$ echo 'Monday at 9' | /usr/bin/grep -oE '(?:Mon|Tues)day'
Monday
$ echo 'Monday at 9' | /usr/bin/sed -E 's/(?:Mon|Tues)day at ([0-9]+)/\1/'
sed: 1: "s/(?:Mon|Tues)day at ([ ...": RE error: repetition-operator operand invalid

The BSD grep -E accepted it and the BSD sed -E rejected it, and I haven’t found out why. GNU tools weren’t available to test. Treat (?:...) as a feature of the Perl-family flavours, and check before using it in grep -E or sed -E.

About the video

The embedded clip is the “noncapture” chapter of DevTips’ “What do () parenthesis and | pipe mean in RegExp? #2 REGEX ULTRA BASICS”, from 16:40 to 22:58. The video was published 22 June 2018 and runs 26 minutes 2 seconds. It is JavaScript. The description says it covers capture groups, non-capture groups (?:) and alternation. I couldn’t read a transcript, so I don’t know whether it shows the split effect or the numbering shift, and the Python findall behaviour above is certainly not in a JavaScript video. The chapter that follows the clip, 22:58 onward, is about online matchers and is excluded. English per its title and description.

What I did not run

GNU grep and GNU sed, regex101’s flavour switcher, and the performance cost of captures. I didn’t measure it, so I won’t claim it is slower.

Next

Numbers are fragile as a pattern grows. Named capture groups gives each box a label instead.

Check yourself

  1. 01You change /(Mon|Tues)day at (\d+)/ to /(?:Mon|Tues)day at (\d+)/. What happens to the number group?

    It becomes group 1. The first group no longer captures, so the whole match is still slot 0 and the digits move up from slot 2 to slot 1.

  2. 02What does 'a1b22c'.split(/(\d+)/) return, and how do you get the pieces without the digits?

    It returns ['a', '1', 'b', '22', 'c'], because split includes captured text. Use /\d+/ or /(?:\d+)/ to get ['a', 'b', 'c'].

  3. 03re.findall(r'(https?|ftp)://\S+', text) returns ['http', 'ftp'] and you wanted the whole URLs. What are two fixes?

    Change the group to non-capturing, (?:https?|ftp)://\S+, so findall returns whole matches. Or wrap the entire pattern in one capturing group so that group is the only one findall sees.

  4. 04Does macOS sed -E accept (?:...)?

    Not on my machine. BSD sed -E failed with 'repetition-operator operand invalid', while BSD grep -E happily accepted the same group. Don't rely on (?:...) in sed or in POSIX tools in general, and test it on the target.

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