Get all overlapping matches of any length

102 Views Asked by At

I'm trying to achieve:

'abc'.scan(regex) #=> ['a', 'b', 'c', 'ab', 'bc', 'abc']

It can be done like this:

(1..'abc'.size).map {|l| 'abc'.scan /(?=(\w{#{l}}))/}.flatten
#=> ["a", "b", "c", "ab", "bc", "abc"]

But I would like to do it in one regex expression.

1

There are 1 best solutions below

7
Sebastián Palma On

What about without regex?:

string = 'abc'
p (1..string.size).flat_map { |e| string.chars.each_cons(e).map(&:join) }
# ["a", "b", "c", "ab", "bc", "abc"]