Get content between parenthesis from String object in Ruby

Use [^()]*? for select text in parenthese :

a = "Hi (a(b)c) ((d)"
# => "Hi (a(b)c) ((d)"
a.gsub(/\([^()]*?\)/) { |x| p x[1..-2]; "w"}
"b"
"d"
# => "Hi (awc) (w"

Try this:

str1 = ""
text = "Hi my name is John (aka Johnator)"

text.sub(/(\(.*?\))/) { str1 = $1 }

puts str1

Edit: Didn't read about leaving the parenthesis!


You can use String#[] with a regular expression:

a = "Hi my name is John (aka Johnator)"
a[/\(.*?\)/]
# => "(aka Johnator)"

Tags:

String

Ruby

Regex