正则表达式返回一个范围的匹配,并包含Ruby中的几个单词之一

时间:2013-06-13 23:49:45

标签: ruby regex

我在Ruby中尝试了以下正则表达式:

"the foodogand the catlada are mouseing".scan(/\b(?=\w{6,12}\b)\w{0,9}(cat|dog|mouse)\w*/)

但不是返回

["foodogand", "catlada", "mouseing"]

我正在

[["dog"],["cat]]  # the results are also in arrays

这里有什么问题? 结果也在数组中,我可以将其弄平,但有没有办法避免它?

2 个答案:

答案 0 :(得分:2)

?:用于最后一组:

"the foodogand the catlada are mouseing".scan(/\b(?=\w{6,12}\b)\w{0,9}(?:cat|dog|mouse)\w*/)
#=> ["foodogand", "catlada", "mouseing"]

来自文档:

  

如果模式包含组,则每个单独的结果本身就是一个包含每个组一个条目的数组。

?:使组无法捕获,避免使用嵌套数组。

答案 1 :(得分:1)

我会稍微清理一下,将第二个\b移到最后,用\w{0,9}替换\w*(前瞻负责长度)

"the foodogand the catlada are mouseing".scan /\b(?=\w{6,12})\w*(?:cat|dog|mouse)\w*\b/
#=> ["foodogand", "catlada", "mouseing"]
相关问题