Home > front end >  Ruby regex for string that starts with s, is followed by 2 consecutive vowels, and has those same 2
Ruby regex for string that starts with s, is followed by 2 consecutive vowels, and has those same 2

Time:04-26

I want to craft a ruby regex that matches strings that meet 3 conditions:

  1. Starts with an s
  2. The s is followed by two vowels
  3. The string has those same two consecutive vowels later in the string

Ex: sourdough starts with s, followed by two vowels (ou), and the two vowels (ou) are in the string later on.

CodePudding user response:

You can capture the two vowels in a matching group and then use a backreference to match it later like this:

/\As([aeiou][aeiou]).*\1/

Explanation:

\A = start of string

s = the character s

([aeiou][aeiou]) = two consecutive vowels, captured in a group

.* = any sequence of 0 or more characters

\1 = backreference to the same group we matched earlier

Test:

irb> /\As([aeiou][aeiou]).*\1/.match('sourdough')
=> #<MatchData "sourdou" 1:"ou">
irb> /\As([aeiou][aeiou]).*\1/.match('sourdoigh')
=> nil
irb> /\As([aeiou][aeiou]).*\1/.match('skourdough')
=> nil
irb> /\As([aeiou][aeiou]).*\1/.match('souou')
=> #<MatchData "souou" 1:"ou">
irb> /\As([aeiou][aeiou]).*\1/.match('kouou')
=> nil
  • Related