Home > Blockchain >  Check if word alternates consonant and vowel
Check if word alternates consonant and vowel

Time:11-17

So I need to check if a word is a pattern of alternating vowel and cosonant (Or consonant and vowel) in Java.

I want to make it a regex but I just came with this incomplete expression:

[aeiouAEIOI][^aeiouAEIOI]

Any ideas? Thanks :)

CodePudding user response:

You can use (?:[aeiouAEIOU][^aeiouAEIOU][aeiouAEIOU]*)*|(?:[^aeiouAEIOU][aeiouAEIOU][^aeiouAEIOU]*)* which has alternate patterns of vowel-consonant-optional_vowel and consonant-vowel--optional_consonant.

Note: (?: is used to start a non-capturing group. Learn more about it here.

public class Main {
    public static void main(String[] args) {
        String pattern = "(?:[aeiouAEIOU][^aeiouAEIOU][aeiouAEIOU]*)*|(?:[^aeiouAEIOU][aeiouAEIOU][^aeiouAEIOU]*)*";
        String arr[] = { "abc", "abu", "eye", "iterate", "abicd" };
        for (String s : arr)
            System.out.println(s   " -> "   s.matches(pattern));
    }
}

Output:

abc -> false
abu -> true
eye -> true
iterate -> true
abicd -> false

CodePudding user response:

One way is to use a lookahead to check if neither two consonants nor to vowels next to each other:

(?i)^(?!.*?(?:[aeiou]{2}|[^aeiou]{2}))[a-z] $

See this demo at regex101 (used i flag for caseless matching, the \n in demo is for staying in line)


Update: Thank you for the comment @Thefourthbird. For matching at least two characters you will need to change the last quantifier: Use [a-z]{2,} (two or more) instead of [a-z] (one or more). For only matching an even amount of characters (2,4,6,8...), change this part to: (?:[a-z]{2})


FYI: If you use this with matches you can drop the ^ start and $ end anchor (see this Java demo).

  • Related