I'm having a tough time getting this to work. I have a string like:
something/([0-9])/([a-z])
And I need regex or a method of getting each match between the parentheses and return an array of matches like:
[
[0-9],
[a-z]
]
The regex I'm using is /\((.+)\)/
which does seem to match the right thing if there is only one set of parenthesis.
How can I get an array like above using any RegExp method in JavaScript? I need to return just that array because the returned items in the array will be looped through to create a URL routing scheme.
This question is related to
javascript
regex
arrays
url
url-routing
Use this expression:
/\(([^()]+)\)/g
e.g:
function()
{
var mts = "something/([0-9])/([a-z])".match(/\(([^()]+)\)/g );
alert(mts[0]);
alert(mts[1]);
}
If s is your string:
s.replace(/^[^(]*\(/, "") // trim everything before first parenthesis
.replace(/\)[^(]*$/, "") // trim everything after last parenthesis
.split(/\)[^(]*\(/); // split between parenthesis
var getMatchingGroups = function(s) {
var r=/\((.*?)\)/g, a=[], m;
while (m = r.exec(s)) {
a.push(m[1]);
}
return a;
};
getMatchingGroups("something/([0-9])/([a-z])"); // => ["[0-9]", "[a-z]"]
Source: Stackoverflow.com