tags:

views:

202

answers:

1

A simple question for most regex experts I know, but I'm trying to return all matches for the words between some curly braces in a sentence; however Ruby is only returning a single match, and I cannot figure out why exactly.

I'm using this example sentence:

sentence = hello {name} is {thing}

with this regex to try and return both "{name}" and "{thing}":

sentence[/\{(.*?)\}/]

However, Ruby is only returning "{name}". Can anyone explain why it doesn't match for both words?

+6  A: 

You're close, but using the wrong method:

sentence = "hello {name} is {thing}"

sentence.scan(/\{(.*?)\}/)
# => [["name"], ["thing"]]
tadman
Ahh, I was looking under the Regex class, I didn't even see that scan method under String. Thanks. I modified it a bit to justsentence.scan(/\{.*?\}/)as I realized with scan, I didn't have to do the groups, and to include the curly braces in the match. Thanks for the help!
japancheese