Arthur Collé
Arthur Collé

Reputation: 2607

Overlapping string matching using regular expressions

Imagine we have some sequence of letters in the form of a string, call it

str = "gcggcataa"

The regular expression

r = /(...)/

matches any three characters, and when I execute the code

str.scan(r)

I get the following output:

["gcg", "gca", "taa"]

However, what if I wanted to scan through and instead of the distinct, non-overlapping strings as above but instead wanted to get this output:

["gcg", "cgg", "ggc", "gca", "cat", "ata", "taa"]

What regular expression would allow this?

I know I could do this with a loop but I don't want to do that

Upvotes: 1

Views: 309

Answers (1)

Sergio Tulentsev
Sergio Tulentsev

Reputation: 230461

str = "gcggcataa"
str.chars.each_cons(3).map(&:join) # => ["gcg", "cgg", "ggc", "gca", "cat", "ata", "taa"]

Upvotes: 1

Related Questions