找到重叠的正则表达式匹配

时间:2016-12-07 22:34:45

标签: ruby regex overlap

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

# Example
"a-b-c".???(/\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

2 个答案:

答案 0 :(得分:7)

在积极前瞻中使用捕获:

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

请参阅Ruby demo

答案 1 :(得分:3)

我建议使用非正则表达式解决方案:

from math import sin,cos,pi
def ellipse(pen, x, y, width, height):
    pen.penup()
    pen.goto(x + width / 2, height)
    pen.pendown()
    penX, penY = pen.pos()
    for i in range(0, 360):
        penX += cos(i*pi/180)*width/180
        penY += sin(i*pi/180)*height/180
        pen.goto(penX, penY)
    pen.penup()

"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"]