Reputation: 146
I'm using Ruby 2.0. I've currently got a string of:
str = "bar [baz] foo [with] another [one]"
str.scan(/\[.*\]/)
The output is:
["[baz] foo [with] another [one]"]
When I would expect it more like:
["[baz]","[with]","[one]"]
So I basically need to put everything between "[]" into an array. Can someone please show me what I'm missing out?
Upvotes: 2
Views: 552
Reputation: 11188
Regexs are greedy by default so your regex grabbing everything from the first [ to the last ]. Make it non-greedy like so:
str.scan(/\[.*?\]/)
Upvotes: 2
Reputation: 5261
Your .*
is greedy, so it doesn't stop until the final bracket.
You need to use a lazy quantifier .*?
or only catch non-brackets: [^\]]*
Upvotes: 4