Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular expression to get value in between parentheses

Tags:

regex

ruby

I am trying to write a regular expression to get the value in between parentheses. I expect a value without parentheses. For example, given:

value = "John sinu.s(14)" 

I expected to get 14.

I tried the following:

value[/\(.*?\)/]

but it gives the result (14). Please help me.

like image 798
ruby.r Avatar asked Oct 12 '25 00:10

ruby.r


2 Answers

You may do that using

value[/\((.*?)\)/, 1]

or

value[/\(([^()]*)\)/, 1]

Use a capturing group and a second argument to extract just the group value.

Note that \((.*?)\) will also match a substring that contains ( char in it, and the second option will only match a substring between parentheses that does not contain ( nor ) since [^()] is a negated character class that matches any char but ( and ).

See the Ruby demo online.

From the Ruby docs:

str[regexp, capture] → new_str or nil
If a Regexp is supplied, the matching portion of the string is returned. If a capture follows the regular expression, which may be a capture group index or name, follows the regular expression that component of the MatchData is returned instead.

In case you need to extract multiple occurrences, use String#scan:

value = "John sinu.s(14) and Jack(156)"
puts value.scan(/\(([^()]*)\)/)
# => [ 14, 156 ]

See another Ruby demo.

like image 193
Wiktor Stribiżew Avatar answered Oct 14 '25 18:10

Wiktor Stribiżew


Another option is to use non-capturing look arounds like this

value[/(?<=\().*(?=\))/]

(?<=\() - positive look behind make sure there is ( but don't capture it
(?=\)) - positive look ahead make sure the regex ends with ) but don't capture it

like image 38
Moti Korets Avatar answered Oct 14 '25 16:10

Moti Korets