Find overlapping Regexp matches

橙三吉。 提交于 2021-01-18 05:39:12

问题


I want to find all matches within a given string including overlapping matches. How could I achieve it?

# 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

回答1:


Use capturing inside a positive lookahead:

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

See Ruby demo




回答2:


I suggest a non-regex solution:

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

or

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

or

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


来源:https://stackoverflow.com/questions/41028602/find-overlapping-regexp-matches

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!