rubyregex

Regex for matching all words between a set of curly braces


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?


Solution

  • You're close, but using the wrong method:

    sentence = "hello {name} is {thing}"
    
    sentence.scan(/\{(.*?)\}/)
    # => [["name"], ["thing"]]