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()
?
views:
129answers:
2
+7
A:
Yes, use capturing (non-escaped) parens:
varname.match(/\(([0-9]+)\)/)[1]
John Millikin
2008-10-01 03:53:11
That's perfect, worked like a charm. Thank you!
Luke Dennis
2008-10-01 04:03:50
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
2008-10-01 04:13:17
+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
2008-10-01 04:03:51