Will Ashley Will Ashley - 5 months ago 9
Ruby Question

Ruby Regex consecutive unique characters

Given the string


I am trying to devise a regex that will capture substrings that contain three unique characters of any quantity.

["aabbaacc", "bbaacc", "aacceeeeaa" "cceeeeaa"].

I've tried something like

/[(\w)\1+]/ or /[(\w)(?!\1)]/

I know those are incomplete. Im not sure If I am on the right track or not.

but I am not sure how to exclude already matched characters, or at least I cannot seem to use ?! properly.


Best of luck with the regex, but if you need a backup plan,....

def pull_subs(str, n)
  arr = str.chars
  (n..str.size).each_with_object([]) { |i,a| arr.each_cons(i) { |b|
    a << b.join if b.uniq.size == n } }

str = "aabbaacceeeeeaa"

pull_subs(str, 3)
  #=> ["baac", "acce", "bbaac", "baacc", "aacce", "accee", "abbaac", "bbaacc",
  #    "aaccee", "acceee", "aabbaac", "abbaacc", "aacceee", "acceeee", "ceeeeea",
  #    "aabbaacc", "aacceeee", "acceeeee", "cceeeeea", "ceeeeeaa", "aacceeeee",
  #    "acceeeeea", "cceeeeeaa", "aacceeeeea", "acceeeeeaa", "aacceeeeeaa"] 
pull_subs(str, 2)
  #=> ["ab", "ba", "ac", "ce", "ea", "aab", "abb", "bba", "baa", "aac", "acc",
  #    "cce", "cee", "eea", "eaa", "aabb", "abba", "bbaa", "aacc", "ccee",
  #    "ceee", "eeea", "eeaa", "aabba", "abbaa", "cceee", "ceeee", "eeeea", 
  #    "eeeaa", "aabbaa", "cceeee", "ceeeee", "eeeeea", "eeeeaa", "cceeeee", 
  #    "eeeeeaa"] 
pull_subs(str, 4)
  #=> ["baacce", "bbaacce", "baaccee", "abbaacce", "bbaaccee", "baacceee", 
  #    "aabbaacce", "abbaaccee", "bbaacceee", "baacceeee", "aabbaaccee", 
  #    "abbaacceee", "bbaacceeee", "baacceeeee", "aabbaacceee", "abbaacceeee",
  #    "bbaacceeeee", "baacceeeeea", "aabbaacceeee", "abbaacceeeee",
  #    "bbaacceeeeea", "baacceeeeeaa", "aabbaacceeeee", "abbaacceeeeea", 
  #    "bbaacceeeeeaa", "aabbaacceeeeea", "abbaacceeeeeaa", "aabbaacceeeeeaa"]