Non-capturing groups in regular expressions
- Published at
- Updated at
- Reading time
It's regular expression time again. 🎉 I don't remember where I saw the following discovery, but after years of using regular expressions, I'm very surprised that I haven't seen it before.
Let's have a look at an example showing capturing groups.
const regex = /(Jane|John|Alison)\s(.*?)\s(Smith|Smuth)/;
The regex defines that I'm looking for a very particular name combination. The name should begin with
Alison, end with
Smuth but also have a middle name.
const result = regex.exec('Jane Isabell Smith'); console.log(result); // 'Jane Isabell Smith' console.log(result); // 'Jane' console.log(result); // 'Isabell' console.log(result); // 'Smith'
exec returned array holds the full string of characters matched followed by the defined groups. Now, to get the middle name, I'd have to look at the regular expression to find out that it is the second group in the regex and will be available at
There's nothing particularly wrong with this but groups I'm not interested in are included in the result which makes it a bit more difficult for me deal with the returned value.
It turns out that you can define groups that are not captured!
const regex = /(?:Jane|John|Alison)\s(.*?)\s(?:Smith|Smuth)/; const result = regex.exec('Jane Isabell Smith'); console.log(result); // 'Jane Isabell Smith' console.log(result); // 'Isabell'
You can use
(?:) to not capture groups and drop them from the result. When you're dealing with complex regular expressions this can be indeed very helpful! 🎉