Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get content between parenthesis from String object in Ruby

Tags:

string

regex

ruby

I have a string like this:

Hi my name is John (aka Johnator).

What is the best way to get what comes between the parentheses (including the parentheses)?

like image 980
Hommer Smith Avatar asked May 14 '12 23:05

Hommer Smith


3 Answers

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

a = "Hi my name is John (aka Johnator)"
a[/\(.*?\)/]
# => "(aka Johnator)"
like image 109
Cade Avatar answered Oct 15 '22 17:10

Cade


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"
like image 33
raubarede Avatar answered Oct 15 '22 18:10

raubarede


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!

like image 24
Sheol Avatar answered Oct 15 '22 18:10

Sheol