Find Regexp matching matches

I want to find all matches in a given string, including matching matches. How can I achieve this?

# 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
+4
source share
2 answers

Use the capture inside the positive view:

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

See Ruby demo

+5
source

I offer a solution without regular expressions:

"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"]
+3
source

Source: https://habr.com/ru/post/1663172/


All Articles