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.
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 aRegexp
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 theMatchData
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With