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\
Use capturing inside a positive lookahead:
"a-b-c-d".scan(/(?=(\w-\w))/).flatten
# => ["a-b", "b-c", "c-d"]
See Ruby demo
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"]