jenuine jenuine - 1 year ago 56
Ruby Question

how to find pair of any two letters that appears at least twice in the string without overlapping

How can i find pair of any two letters that appears at least twice in the string without overlapping?

For example, in the string '

adjkoedjeoieadkkji
' i should find
ad
because it happens twice.

In the string '
adjkobbbeoieadkkji
' i should NOT find
bb
because the two occurrences overlap.

I've tried with
/^([a-z]{2}).*(\1)$/
it matches only '
abab
'
still trying from my side please help me someone experts in regex

Answer Source

Your string does not necessarily end after finding \1. So you are getting nothing. You can use

^.*?([a-z]{2}).*?(\1).*$

Regex Demo