17

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)?

Hommer Smith
  • 26,772
  • 56
  • 167
  • 296

3 Answers3

36

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

a = "Hi my name is John (aka Johnator)"
a[/\(.*?\)/]
# => "(aka Johnator)"
Cade
  • 3,151
  • 18
  • 22
  • 1
    what do you get for `"Hi my name is John (aka Surprise Bat /\\(*)(*)/\\)"`? – dbenhur May 14 '12 at 23:34
  • @dbenhur half a Surprise Bat. `[/\(.*\)/]` will prevent the slaughter. – Cade May 14 '12 at 23:39
  • @Cade ok, but now we're hosed with `"Hi my name is John (aka Surprise Bat /\\(*)(*)/\\) and this is my friend William (aka Bill)"`. Regexp has a hard time with arbitrary nesting http://stackoverflow.com/a/133684/1074296. – dbenhur May 14 '12 at 23:46
  • 5
    @dbenhur Sure. But these are straw men. It also won't help with `(It's () hard () to () write () a ()( (regex) )() when () the () input () (can () be () anything!))` – Cade May 14 '12 at 23:56
  • 1
    @venkatareddy The question mark changes it from a greedy match, which will match until the last closing parenthesis, to a lazy match, which will match until the first closing parenthesis. You can read more about greedy vs. lazy matching here: http://www.regular-expressions.info/repeat.html#greedy – Cade Sep 18 '15 at 14:19
3

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"
Sebastián Palma
  • 32,692
  • 6
  • 40
  • 59
raubarede
  • 423
  • 3
  • 6
1

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!

Sheol
  • 164
  • 1
  • 3
  • 13