I want to craft a ruby regex that matches strings that meet 3 conditions:
- Starts with an s
- The s is followed by two vowels
- 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
