Regex: How to Get the Last Matching Group
Getting the last match or capture with a regex depends on what "last" means. Compare repeated groups, last-match patterns, lastindex, and reversal pitfalls.
"Get the last matching group" can describe three different problems, and each needs a different technique. Choosing a pattern before deciding which one you have is the most common source of wrong results. This review explains each meaning, shows the usual approaches, and points out where each one stops being reliable or portable.
What "last" can mean
- The last capture of a repeated group, such as the final digit captured by (\d)+.
- The last match of a pattern in the whole string, such as the final number in a log line.
- The highest-numbered or most recently closed group that took part in a match, when a pattern has several optional or alternative groups.
The last capture of a repeated group
In most engines, a capturing group inside a quantifier is overwritten on each iteration, so only the final repetition survives. Applying (\d)+ to "123" leaves group 1 holding "3". That is convenient when the final iteration is what you want, and a trap when you expected every iteration. .NET is the notable exception: each Group object exposes a Captures collection containing every iteration, while Group.Value still returns the last one. In other engines, if you need every repetition, match the repeated item with a global search instead of relying on one group.
# Python
import re
m = re.search(r"(\d)+", "123")
print(m.group(1)) # 3 (earlier iterations are discarded)
// JavaScript
/(\d)+/.exec("123")[1]; // "3"
The last match in a string
Regex engines search from left to right, so "find the last occurrence" is not something a plain search does by default. There are three common workarounds, in order of reliability.
Iterate over all matches and keep the final one
This is the most transparent option and works in every engine. The pattern stays simple, and the "last" logic lives in ordinary code where it is easy to read and test. In Python, note that re.findall returns the group contents when the pattern contains one group, and tuples when it contains several.
# Python
import re
matches = re.findall(r"\d+", "order 12, item 345")
last = matches[-1] if matches else None # "345"
// JavaScript (matchAll requires the g flag)
const all = [..."order 12, item 345".matchAll(/\d+/g)];
const last = all.at(-1)?.[0]; // "345"
A greedy prefix
A pattern like .(\d+) looks as if it should capture the last number, but the greedy . gives back only as many characters as the rest of the pattern needs. Against "order 12, item 345" the group captures just "5". The fix is to require a boundary in front of the captured run, for example a negative lookbehind that forbids a digit immediately before it.
Pattern Input Group 1
.*(\d+) order 12, item 345 5
.*(?<!\d)(\d+) order 12, item 345 345
A negative lookahead
The pattern (\d+)(?!.*\d) matches a run of digits that is not followed by any further digit, which makes it the last one. Two caveats apply. First, the dot does not match line breaks unless a dot-all flag is set, so on multi-line input the first result is the last number on the first line that contains a number, not the last number in the text; use [\s\S] or the dot-all flag to span lines. Second, the lookahead rescans the remainder of the input for every candidate, so the cost grows quickly on long inputs with many candidates.
# Python
re.search(r"(\d+)(?![\s\S]*\d)", text)
// JavaScript
/(\d+)(?![\s\S]*\d)/.exec(text)
The highest or most recently closed group
When a pattern has alternatives such as (a)|(b)|(c), you may want to know which group actually matched. Python provides match.lastindex and, for named groups, match.lastgroup. Be aware that lastindex refers to the last group to close, so with nested groups an outer group can be reported: per the Python documentation, ((a)b) applied to "ab" gives a lastindex of 1, not 2. Perl offers $+ for the highest-numbered group that participated and $^N for the most recently closed group. JavaScript, Java and .NET have no single built-in accessor; the usual approach is to scan groups from the highest index downward and take the first one that participated (undefined in JavaScript, null in Java, and Success set to false in .NET indicate a group that did not participate).
# Python
m = re.match(r"(a)|(b)|(c)", "b")
m.lastindex # 2
// JavaScript: highest-numbered group that participated
const m = /(a)|(b)|(c)/.exec("b");
const idx = m.findLastIndex((v, i) => i > 0 && v !== undefined); // 2
The reversal trick, and why it is fragile
A frequently suggested workaround is to reverse the string, apply a reversed pattern, take the first match, and reverse the result back. Unlike a visual mirror effect, this changes the stored order of characters, so any flaw in the reversal changes the data itself. It can work for plain ASCII input, but it breaks with text that uses combining marks or multi-code-point emoji. Reversing by code point separates a combining accent from its base letter. In JavaScript, splitting with split("") works on UTF-16 code units and tears astral characters such as most emoji into lone surrogates; spreading the string into code points avoids that but still breaks zero-width-joiner sequences and two-letter flag sequences, which can turn into a different flag or plain letters. Grapheme-aware reversal (for example with Intl.Segmenter in JavaScript) avoids those problems but adds complexity, and reversing the pattern itself is not mechanical once lookarounds, anchors or quantified groups are involved. The iterate-and-take-last approach is almost always the better choice.
s = "cafe\u0301 42" # displays as "café 42" (e + combining acute accent)
s[::-1] # "24 " + "\u0301" + "efac": the accent now attaches to the space
Will the pattern still work after you copy it elsewhere?
Regular expressions are not one language. A pattern that behaves correctly in one tester or runtime can fail, or silently return a different group, in another. The features most relevant to finding the last match differ as follows; support also varies by version, so confirm against the documentation for the version you deploy.
| Feature | Python re | JavaScript | .NET | Perl / PCRE |
| All captures of a repeated group | No, last only | No, last only | Yes, Group.Captures | No, last only |
| Lookbehind (?<!...) | Fixed width only | Yes (ES2018 and later) | Yes, variable width | Restricted length, version-dependent |
| \K (reset match start) | No | No | No | Yes |
| Last-group accessor | lastindex, lastgroup | None built in | None built in | Perl: $+ and $^N |
| Dot matches newline | re.DOTALL or (?s) | s flag | RegexOptions.Singleline | /s or (?s) |
When moving a pattern out of an online tester, check three things: that the tester's flavor setting matches your target runtime, that flags such as global, multi-line and dot-all are carried over (they are often set outside the pattern text and get lost on copy), and that backslashes are escaped correctly for the destination. Java string literals and non-raw Python strings need doubled backslashes, while JavaScript regex literals and Python raw strings do not.
Is a regex the right tool for this?
For most extraction tasks, the recommended approach is to match all occurrences with a simple pattern and take the final one in code. It is readable, portable across engines and free of the greedy-prefix and multi-line pitfalls. A single-expression solution, using a greedy prefix with a boundary or a negative lookahead, is worth it mainly when you are limited to one pattern, such as a configuration field, a search box or a validation attribute. In that case, test it against input with several candidates, no candidates, candidates at the very start and end, and line breaks. When the delimiter is fixed, plain string operations are preferable to any regex: splitting on the separator and taking the last element, or using rsplit or lastIndexOf, is clearer and harder to get wrong. Avoid the reversal trick unless the input is guaranteed to be simple ASCII.
Limits of this review
The examples reflect documented engine behavior; no benchmarks, performance measurements or comparisons of specific regex testing tools were available for this review. Feature support, particularly for lookbehind and Unicode handling, changes between engine versions, so verify the exact behavior in the runtime and version you rely on.