Mrs. Ratna's PO chat is printed, and you pick up three highlighters: one colour for the day, one for the month, one for the year. You mark every date, then copy what each colour holds into its own column in the order book.
In a regex, the highlighters are parentheses ( ), and the part of the pattern inside them is called a group. Each pair of parentheses is one colour, and they are numbered from the left. Parentheses do two jobs: they join several characters into one unit, so a quantifier repeats all of them, and they capture the text that matched inside them, so you can take it out again.
Parentheses join several characters
A quantifier repeats only the one thing right before it. Parentheses make that "one thing" several characters at once.
console.log("hahaha".match(/ha+/)[0]); // 'ha'
console.log("hahaha".match(/(ha)+/)[0]); // 'hahaha'
console.log(chat.match(/07\d{3}(-\d{3})+/g)); // ['07700-900-123']
ha+repeats only the lettera: it matcheshaaaa, nothahaha.(ha)+repeats the pairha.(-\d{3})+repeats "a dash, then three digits", so Dina's number07700-900-123comes out whole, both dash groups included.
Capturing groups: take the parts
Each pair of parentheses also stores the text that matched inside it. Without the g flag, match() returns an array: index 0 holds the whole match, then one element per group, in the order of the opening ( from the left.
const m = chat.match(/\[(\d{2})\/(\d{2})\/(\d{2})/);
console.log(m[0]); // '[12/03/26' the whole match
console.log(m[1]); // '12' group 1: day
console.log(m[2]); // '03' group 2: month
console.log(m[3]); // '26' group 3: year
console.log(m.length); // 4
console.log(m.index); // 0 where it sits in the chat
\[and\/take part in the match but aren't captured: only what's inside the parentheses is stored.- Three groups make a 4-element array. Groups start at number 1, because
m[0]is already taken by the whole match. Same with"abc".match(/(a)(b)(c)/): its length is 4. In"2024-01-15".match(/(\d{4})-(\d{2})-(\d{2})/),m[1]is"2024". - Nothing matches?
match()returnsnull. Check before you readm[1].
What a group holds can be used again in replace(): $1, $2 in the replacement mean what group 1 and group 2 hold.
const delivery = chat.match(/on (\d{2})\/(\d{2})/);
console.log(delivery[1], delivery[2]); // '25' '03'
console.log("25/03".replace(/^(\d{2})\/(\d{2})$/, "$2-$1")); // '03-25'
console.log("25/03 and 26/03".match(/^(\d{2})\/(\d{2})$/)); // null
$2-$1puts it back together: the month first, a dash, then the day.^and$make the whole text have to be a date. Any other text getsnull, not a fake date.
Named groups: (?<name>...)
m[1] and m[2] are easy to mix up. Give a group a name with (?<name>...), then read it from m.groups.
const w = chat.match(/\[(?<day>\d{2})\/(?<month>\d{2})\/(?<year>\d{2})/);
console.log(w.groups.day, w.groups.month, w.groups.year); // '12' '03' '26'
console.log(w[1]); // '12' its number is still there
console.log("25/03".replace(/(?<day>\d{2})\/(?<month>\d{2})/, "$<month>-$<day>")); // '03-25'
In a replacement, a named group is called with $<name>.
Non-capturing groups: (?:...)
Sometimes you need parentheses only to join, not to store. Write (?:...): still one unit, but it stays out of the result.
const a = chat.match(/07\d{3}(-\d{3})+/);
console.log(a[0], a[1], a.length); // '07700-900-123' '-123' 2
const b = chat.match(/07\d{3}(?:-\d{3})+/);
console.log(b[0], b[1], b.length); // '07700-900-123' undefined 1
The result is cleaner, and the numbers of the groups you care about don't shift. For example /^(?:https?):\/\/(.+)/: https isn't stored, so the address stays group 1.
Backreferences: \1
\1 inside a pattern means "exactly the same text group 1 holds". WhatsApp formatting uses this idea: *bold*, _italic_, ~strike~. The closing mark has to be the same as the opening one.
console.log(chat.match(/([*_~])[^*_~]+\1/g)); // ['*Tart*', '*Cheese Sticks*', '*Snowballs*']
console.log("*Tart_ and *Cheese Sticks*".match(/([*_~])[^*_~]+\1/g)); // ['*Cheese Sticks*']
console.log("deliver deliver on 25/03".match(/\b(\w+) \1\b/)[1]); // 'deliver'
([*_~])captures the opening mark,\1asks for the same mark at the close.*Tart_is turned down because it opens with*and closes with_.\b(\w+) \1\bfinds a word written twice in a row.- For a named group, write
\k<name>.
A quantifier outside the parentheses
Guess first: "PO-0412".match(/PO-(\d)+/) matches PO-0412, but does group 1 hold 0412 or only 2?
console.log("PO-0412".match(/PO-(\d)+/)[1]); // '2'
console.log("PO-0412".match(/PO-(\d+)/)[1]); // '0412'
The repeated group does match four times, but it stores only the last repetition. Each round overwrites the one before, so what's left is 2. Want the whole number? Put the quantifier inside the parentheses: (\d+).
⚠️ Why is the group gone, an error, or undefined?
match()with thegflag drops the groups.chat.match(/PO-(\d+)/g)only gives['PO-0412', 'PO-0413']. Need the groups of every match? UsematchAll():[...chat.matchAll(/PO-(\d+)/g)].map((m) => m[1])gives['0412', '0413']. More in the Regex in JavaScript lesson.- Reading a group from
null."hello".match(/(\d+)/)[1]throwsTypeError: Cannot read properties of null (reading '1'). Keep the result and check it first. - Counting groups from 0.
m[0]is the whole match. The first group ism[1]. - An optional group that didn't take part holds
undefined:"PO-0412".match(/PO-(x)?(\d+)/)[1].
TL;DR: Parentheses ( ) join several characters for a quantifier, like (ha)+ and (-\d{3})+, and capture what's inside. Without g, match() gives [whole, group1, group2, ...], so "abc".match(/(a)(b)(c)/).length is 4 and groups start at m[1]. In replace(), $1 and $<name> use what a group holds. (?<name>...) gives a name, read through m.groups.name. (?:...) joins without storing. \1 asks for the same text as group 1. A quantifier outside the parentheses stores only the last repetition: use (\d+), not (\d)+. match() with g drops the groups; use matchAll().
⚡ Parentheses join and capture
Write:
const m = chat.match(/\[(\d{2})\/(\d{2})\/(\d{2})/);
console.log(m[1], m[2], m[3]); // '12' '03' '26'
Meaning: Each pair of parentheses is one group, numbered from the left. m[0] holds the whole match, so the first group is m[1].
⚡ Named groups, and groups that don't store
Write:
const b = chat.match(/07\d{3}(?:-\d{3})+/);
console.log(b[0], b[1], b.length); // '07700-900-123' undefined 1
Meaning: (?:...) is still one unit, but it stays out of the result, so the other groups keep their numbers. In /^(?:https?):\/\/(.+)/, https isn't stored, so the address stays group 1. (?<name>...) gives a group a name, read through m.groups.name.
⚡ A quantifier outside the parentheses
Write:
console.log("PO-0412".match(/PO-(\d)+/)[1]);
Guess first: PO-0412 matches. Does group 1 hold 0412 or only 2?
2. The repeated group does match four times, but it stores only the last repetition. Want the whole number? Put the quantifier inside: (\d+).
Meaning: (\d)+ stores the last repetition, (\d+) stores all of it.