views:

129

answers:

2

Say I've got a string, "foo (123) bar", and I want to retrieve all numbers surrounded by the delimiters "(" and ")". If I use varname.match(/\([0-9]+\)/), my delimeters are included in the response, and I get "(123)" when what I really want is "123". Is there a way I can retrieve only a portion of the matched string without following it up with varname.replace()?

+7  A: 

Yes, use capturing (non-escaped) parens:

varname.match(/\(([0-9]+)\)/)[1]
John Millikin
That's perfect, worked like a charm. Thank you!
Luke Dennis
The '[1]' is the part the picks the first substring match. If it was '[0]' instead, it would return the entire match (e.g. '(123)')
Steven Oxley
+1  A: 

For a really good site on Regular Expressions try Regular-Expressions.info. There you will find tutorials, reference, examples, and more. This site has helped me more than once.

TomC