Access All Captures in JavaScript Regular Expressions
The problem arises when trying to capture multiple groups in a JavaScript regular expression, where only the last capture is retained.
Consider the following example:
"foo bar baz".match(/^(\s*\w+)+$/)
Instead of returning all matches like ["foo", "bar", "baz"], it only returns ["baz"]. This behavior occurs because repeated capturing groups overwrite previous captures.
To resolve this, consider alternative approaches:
For instance, to capture a sequence of words enclosed in < > and split them on ;, consider the following example:
var text = "a;b;<c;d;e;f>;g;h;i;<no no no>;j;k;<xx;yy;zz>"; var r = /<(\w+(;\w+)*)>/g; var match; while ((match = r.exec(text)) != null) { print(match[1].split(";")); }
This regex splits the captured sequence into individual words.
References:
The above is the detailed content of How to Capture Multiple Groups in JavaScript Regular Expressions?. For more information, please follow other related articles on the PHP Chinese website!