Ryan
Ryan

Reputation: 146

Extracting Ruby string within a pattern within a scan or regex pattern

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

Answers (2)

Dave Sexton
Dave Sexton

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

Brian Stephens
Brian Stephens

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

Related Questions