Regex Groups and Assertions

Updated · 6 min read
mediumES2026javascriptregexcapture-groupslookahead

Groups let a regular expression do more than say "yes, it matches": they capture parts of the match so you can extract them, like the year, month and day from a date, or the area code from a phone number. Alternation chooses between options. Lookahead and lookbehind assertions check what comes before or after a position without including it in the match. Backreferences require the same text to appear twice. Together they turn regular expressions into a parsing tool.

In One Minute

  • ( ) creates a capture group; the match result holds each group's text by number: match[1], match[2].
  • (?<name> ) creates a named group: match.groups.name. Prefer names for anything you'll read later.
  • (?: ) groups without capturing, for applying a quantifier or alternation to several characters.
  • a|b matches either side: (card|check|ach).
  • Lookahead (?=...), (?!...) and lookbehind (?<=...), (?<!...) check context without consuming it.

Capture Groups

Parentheses group part of a pattern and remember what it matched:

capture.js▶ Try it
const match = "Due 2026-01-05".match(/(\d{4})-(\d{2})-(\d{2})/);
 
console.log(match[0]);
console.log(match[1], match[2], match[3]);
console.log(match.index);
 
const [, year, month, day] = match;
console.log(`${Number(month)}/${Number(day)}/${year}`);
Output
2026-01-05
2026 01 05
4
1/5/2026

Explanation: without the g flag, match returns an array: index 0 is the whole match, and indexes 1, 2, 3 are the groups, numbered by the position of their opening parenthesis. The array also has an index property (where the match started). Destructuring with a leading comma skips the whole match.

Named Groups

Numbered groups break when you add another group earlier in the pattern. Named groups ((?<name>...)) stay readable and stable:

named.js▶ Try it
const DATE = /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/;
const { year, month, day } = "Paid on 2026-02-14".match(DATE).groups;
 
console.log(year, month, day);
console.log("2026-02-14".replace(DATE, "$<month>/$<day>/$<year>"));
Output
2026 02 14
02/14/2026

match.groups is an object with one property per named group, ideal for destructuring. In a replacement string, $<name> inserts a named group (and $1, $2 insert numbered ones).

Non-Capturing Groups

Sometimes you need parentheses only to group, for example to apply a quantifier to several characters, without capturing. Use (?:...):

non-capturing.js▶ Try it
const phone = /^(?:\+1[\s-]?)?\(?(\d{3})\)?[\s.-]?(\d{3})[-.]?(\d{4})$/;
 
console.log("+1 (214) 555-0100".match(phone).slice(1));
console.log("214.555.0100".match(phone).slice(1));
Output
['214', '555', '0100']
['214', '555', '0100']

The optional country code (?:\+1[\s-]?)? is grouped so the final ? applies to all of it, but it isn't captured, so the three real groups stay numbered 1 to 3.

Alternation

The | operator matches either the pattern on its left or the one on its right. It has the lowest precedence, so group it to limit its reach:

alternation.js▶ Try it
const method = /^(?:card|check|ach)$/i;
console.log(method.test("Check"), method.test("cash"));
 
console.log(/^card|check$/.test("my check"));
console.log(/^(?:card|check)$/.test("my check"));
 
console.log("Paid by card, then check, then card".match(/card|check/g));
Output
true false
true
false
['card', 'check', 'card']

/^card|check$/ means "starts with card" or "ends with check", which is why "my check" matches. Wrapping the alternatives in a group, ^(?:card|check)$, applies the anchors to both.

Lookahead and Lookbehind

Assertions test what is next to the current position without including it in the match. They are zero-width, like ^ and \b:

SyntaxNameMeans
X(?=Y)Positive lookaheadX, followed by Y
X(?!Y)Negative lookaheadX, not followed by Y
(?<=Y)XPositive lookbehindX, preceded by Y
(?<!Y)XNegative lookbehindX, not preceded by Y
lookaround.js▶ Try it
const text = "Tuition $400, books 85 USD, lab $45, refund -$20";
 
console.log(text.match(/(?<=\$)\d+/g));
console.log(text.match(/\d+(?= USD)/g));
console.log(text.match(/(?<!-)\$\d+/g));
Output
['400', '45', '20']
['85']
['$400', '$45']

Explanation: (?<=\$)\d+ finds digits preceded by a dollar sign, but the $ itself isn't part of the match. \d+(?= USD) finds digits followed by " USD". (?<!-)\$\d+ finds dollar amounts not preceded by a minus sign, excluding the refund.

Lookahead for Password Rules

Several lookaheads at the start of a pattern can each check one rule, all from the same position:

password.js▶ Try it
const STRONG = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d).{12,}$/;
 
for (const pw of ["feetracker2026", "FeeTracker2026", "Fee2026"]) {
  console.log(pw.padEnd(16), STRONG.test(pw));
}
Output
feetracker2026   false
FeeTracker2026   true
Fee2026          false

Each (?=.*X) checks "somewhere ahead there is an X" and then returns to the start, so the rules are independent. (Real password policies favor length over character rules; this is a teaching example of the technique.)

Backreferences

A backreference matches the same text a group already captured: \1 for group 1, \k<name> for a named group:

backreference.js▶ Try it
console.log("the the fee is is due".match(/\b(\w+) \1\b/g));
 
const QUOTED = /(?<q>["'])(?<text>.*?)\k<q>/;
console.log(`Note: "paid in full" ok`.match(QUOTED).groups.text);
console.log(`Note: 'mixed" quotes`.match(QUOTED));
Output
['the the', 'is is']
paid in full
null

The first pattern finds doubled words. The second matches text in quotes only when the closing quote is the same kind as the opening one.

Group Indices with the d Flag

With the d flag (ES2022), the match has an indices property giving the start and end of the whole match and every group, which is useful for highlighting:

indices.js▶ Try it
const m = "Pay $120 now".match(/\$(?<amount>\d+)/d);
console.log(m.indices[0], m.indices.groups.amount);
Output
[4, 8] [5, 8]

In Practice

The Fee Tracker reads lines from a bank statement in mixed formats, extracting the date, payer and amount with one named-group pattern, and converts the date to ISO:

statement.js▶ Try it
const LINE = /^(?<month>\d{1,2})\/(?<day>\d{1,2})\/(?<year>\d{4})\s+(?<payer>[\p{L} ]+?)\s+\$(?<amount>\d+(?:\.\d{2})?)$/u;
 
const lines = ["1/5/2026  Navika Anamaneni  $120.00", "01/12/2026 Zoë Park $85", "bad line"];
 
for (const line of lines) {
  const m = line.match(LINE);
  if (!m) {
    console.log("Skipped:", line);
    continue;
  }
  const { month, day, year, payer, amount } = m.groups;
  const iso = `${year}-${month.padStart(2, "0")}-${day.padStart(2, "0")}`;
  console.log(iso, payer, Number(amount));
}
Output
2026-01-05 Navika Anamaneni 120
2026-01-12 Zoë Park 85
Skipped: bad line

The lazy +? in the payer group stops before the spaces that precede the amount, and \p{L} (with the u flag) accepts names like Zoë.

Common Mistakes

Reading numbered groups after editing the pattern. Adding a group shifts the numbers. Use named groups.

Unwrapped alternation with anchors. /^a|b$/ isn't "a or b, whole string". Write /^(?:a|b)$/.

Capturing when you only need grouping. Extra groups clutter results. Use (?:...).

Expecting match with g to return groups. With g, match returns only the matched strings. Use matchAll for groups of every match (next lesson).

Practice

Challenge: Write a pattern with named groups that extracts the dollars and cents from strings like "$1,234.50", allowing optional thousands commas, and print them as numbers.

Show solution
money.js▶ Try it
const MONEY = /^\$(?<dollars>\d{1,3}(?:,\d{3})*)\.(?<cents>\d{2})$/;
 
for (const s of ["$1,234.50", "$85.00", "$12,34.00"]) {
  const m = s.match(MONEY);
  if (!m) {
    console.log(s, "invalid");
    continue;
  }
  console.log(Number(m.groups.dollars.replaceAll(",", "")), Number(m.groups.cents));
}
Output
1234 50
85 0
$12,34.00 invalid

Quick check: Groups and assertions

3 questions
1In "2026-01-05".match(/(\d{4})-(\d{2})-(\d{2})/), what is match[2]?
2What does (?:abc) do?
3What does \d+(?= USD) match in "85 USD"?

Key Takeaways

SyntaxMeaning
(x)Capture group
(?<name>x)Named group
(?:x)Group, no capture
a|bEither
x(?=y), x(?!y)Lookahead
(?<=y)x, (?<!y)xLookbehind
\1, \k<name>Backreference

Was this tutorial helpful?

Lesson 65 of 139