查找重叠的REGEXP匹配



我想在给定的字符串中找到包括重叠匹配的所有匹配项。我怎么能实现它?

# Example
"a-b-c-d".???(/w-w/)  # => ["a-b", "b-c", "c-d"] expected
# Solution without overlapped results
"a-b-c-d".scan(/w-w/) # => ["a-b", "c-d"], but "b-c" is missing

使用捕获积极的lookahead:

"a-b-c-d".scan(/(?=(w-w))/).flatten
 # => ["a-b", "b-c", "c-d"]

请参阅Ruby Demo

我建议一个非regex解决方案:

"a-b-c-d".delete('-').each_char.each_cons(2).map { |s| s.join('-') }
  #=> ["a-b", "b-c", "c-d"]

"a-b-c-d".each_char.each_cons(3).select.with_index { |_,i| i.even? }.map(&:join)
  #=> ["a-b", "b-c", "c-d"]

enum = "a-b-c-d".each_char
a = []
loop do
  a << "%s%s%s" % [enum.next, enum.next, enum.peek]
end
a #=> ["a-b", "b-c", "c-d"]

相关内容

  • 没有找到相关文章

最新更新