Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RegEx to match stuff between parentheses

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.

like image 476
Oscar Godson Avatar asked Jun 01 '11 22:06

Oscar Godson


People also ask

How do you use parentheses in regex?

By placing part of a regular expression inside round brackets or parentheses, you can group that part of the regular expression together. This allows you to apply a quantifier to the entire group or to restrict alternation to part of the regex. Only parentheses can be used for grouping.

What does '$' mean in regex?

$ means "Match the end of the string" (the position after the last character in the string).

How do you match everything including newline regex?

The dot matches all except newlines (\r\n). So use \s\S, which will match ALL characters.

How do I match a pattern in regex?

Regular expressions, called regexes for short, are descriptions for a pattern of text. For example, a \d in a regex stands for a digit character — that is, any single numeral 0 to 9. Following regex is used in Python to match a string of three numbers, a hyphen, three more numbers, another hyphen, and four numbers.


2 Answers

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 parens that do not, themselves, contain parens.

like image 65
Rob Raisch Avatar answered Sep 27 '22 15:09

Rob Raisch


Use this expression:

/\(([^()]+)\)/g 

e.g:

function() {     var mts = "something/([0-9])/([a-z])".match(/\(([^()]+)\)/g );     alert(mts[0]);     alert(mts[1]); } 
like image 42
Chandu Avatar answered Sep 27 '22 15:09

Chandu