1

I have the following regular expression that is supposed to match all words that have parenthesis around them (including the parenthesis) but it only matches one case. What am I doing wrong?

"(e), (f), and (g)".match(/\(\w+\)/)
=> #<MatchData "(e)">

The output should be:

=> #<MatchData "(e)", 1: "(f)", 2: "(g)">
Artem Kalinchuk
  • 6,232
  • 5
  • 41
  • 55
  • 1
    Not a Ruby coder, but did you try [`scan()`](http://stackoverflow.com/a/80387/1438393) instead? – Amal Murali Aug 28 '14 at 15:30
  • Side note, you may want to use the expression [`/\([^)]+\)/`](http://www.rubular.com/r/SkpBW6ghDC) if there is a chance for non-`\w` characters. – Sam Aug 28 '14 at 15:33
  • Does Ruby 'match' stop after the first match? Does it take the global flag `//g` ? –  Aug 28 '14 at 15:35
  • 1
    `scan` is what you want, unless you specifically need a `MatchData` – Dave Newton Aug 28 '14 at 15:36

1 Answers1

6

Use scan() instead. It returns an array with all the matches. match() will only return the first match.

"(e), (f), and (g)".scan(/\(\w+\)/)
the Tin Man
  • 155,156
  • 41
  • 207
  • 295
Tim Zimmermann
  • 5,632
  • 3
  • 27
  • 35