How can I get the position and captured groups from a regex match?
Quick answer
In Python, keep the match object returned by re.search(): use group(0) for the full match, group(1) and later numbers for captures, and start() for the match’s start. In JavaScript, for a non-global regex, match() returns an array with the full match and captures; read its index property for the start. The result shapes differ, so use the language-specific access pattern.
The question, the details, the next step.
A practical checklist
Confirm which language and matching method your code uses.
Separate the full match from the captures when reading the result.
Use the language-specific start-position accessor.
In JavaScript, check whether the regex has the
gflag before relying onmatch()for captures.Handle the possibility that the pattern finds no match.
A few more useful answers
In Python, how can I get all the captured groups at once?
Call groups() on a successful Python match object to get its captured groups. Use group(0) separately when you also need the complete match. [S1]
In JavaScript, why are my captures missing from `match()`?
Check whether the regex has the global g flag. With that flag, String.prototype.match() does not return capture groups; use RegExp.prototype.exec() or String.prototype.matchAll() when global matching and captures are needed. [S2]
Sources
References used for this guide.
- [S1] Python 3 regular-expression operations: Match objects docs.python.org · Checked
- [S2] MDN: JavaScript String.prototype.match() results developer.mozilla.org · Checked
