admin管理员组

文章数量:1136515

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.

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.

Share Improve this question asked Jun 1, 2011 at 22:13 Oscar GodsonOscar Godson 32.7k42 gold badges125 silver badges206 bronze badges 2
  • 2 When you say "one set of parentheses", are you referring to nested parentheses? It's basically beyond the power of regular expressions to understand the whole "balanced parentheses" thing. – Pointy Commented Jun 1, 2011 at 22:15
  • 1 Anything inside of the (). So if the string was something/([0-9])/((a)(b)) it'd return [ [0-9], (a)(b) ]. Im not going to validate these, just throwing em inside a new RegExp() – Oscar Godson Commented Jun 1, 2011 at 22:20
Add a comment  | 

4 Answers 4

Reset to default 159

You need to make your regex pattern 'non-greedy' by adding a ? after the .+

By default, * and + are greedy in that they will match as long a string of chars as possible, ignoring any matches that might occur within the string.

Non-greedy makes the pattern only match the shortest possible match.

See Watch Out for The Greediness! for a better explanation.

Or alternately, change your regex to

\(([^\)]+)\)

which will match any grouping of parentheses that do not, themselves, contain parentheses.

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]"]

本文标签: javascriptRegEx to match stuff between parenthesesStack Overflow