在扫描或regex模式内的模式中提取Ruby字符串。

时间:2022-06-01 20:42:10

I'm using Ruby 2.0. I've currently got a string of:

我用Ruby 2.0。我现在有一连串:

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?

所以我基本上需要把"[]"之间的所有东西都放到一个数组中。谁能告诉我我遗漏了什么吗?

2 个解决方案

#1


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: [^\]]*

你需要使用一个懒惰的量词。*?或者只抓摘要:[^ \]]*

#2


2  

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

默认情况下,regex是贪婪的,因此您的regex将从第一个[到最后一个]获取所有内容。让它变得不贪婪:

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

#1


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: [^\]]*

你需要使用一个懒惰的量词。*?或者只抓摘要:[^ \]]*

#2


2  

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

默认情况下,regex是贪婪的,因此您的regex将从第一个[到最后一个]获取所有内容。让它变得不贪婪:

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