2

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?

1
  • 1
    str.scan(/\[.*?\]/) #=> ["[baz]", "[with]", "[one]"] Commented Aug 1, 2013 at 12:55

2 Answers 2

4

Your .* is greedy, so it doesn't stop until the final bracket.

You need to use a lazy quantifier .*? or only catch non-brackets: [^\]]*

Sign up to request clarification or add additional context in comments.

Comments

3

Regexs are greedy by default so your regex grabbing everything from the first [ to the last ]. Make it non-greedy like so:

str.scan(/\[.*?\]/)

1 Comment

This one worked perfectly thanks - same conclusion as Brian's answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.