0

I'm working on MOOC Java II problem 10.15:

Create the method public boolean allVowels(String string) that uses a regular expression to check whether all the characters in the parameter string are vowels.

The question wants us to detect any strings that have one or more consonants.

This is my method:

    public boolean allVowels(String string){
        String regex = "[b-df-hj-np-tv-z]";

        if(string.matches(regex)){
            return false;
        }

        return true;
    }

Why does this method fail to detect a string that has a consonant mixed with a vowel e.g. "ab"?

I thought that [b-df-hj-np-tv-z] means "return a match if the string contains any of these characters in this list"... so why does a string like "ab" fail to return false in my method?

Keep in mind my regex pattern does return a match if I use something like regex101.com e.g. enter image description here

I've tried playing around with the regex pattern, but I can't seem to pass the MOOC test case... not sure what I'm doing wrong :-(

  • For that to work, your string would have to be one character long. When you've corrected that, the code is a one liner: `return ! regex.matches(string);` But it would be better the other way around – g00se Aug 15 '23 at 13:16
  • `String.matches` try to match the whole regex, here it fails to. A valid regex for your case would be `.*[b-df-hj-np-tv-z].*` or the other way around like just `return string.matches(".*[aeiouy].*")` – azro Aug 15 '23 at 13:17
  • I would start with the approach that I only want to match vowels - so a pattern like `\b[aeiou]+\b` will only match vowels within a word. The `+` means to match 1 or more vowels, the `\b` surrounds the 'vowels' with a word boundary. – JohnXF Aug 15 '23 at 13:17
  • Note that when you have a method that return a boolean based on a condition : you can directly return the condition (or it's opposite) – azro Aug 15 '23 at 13:18
  • @g00se is that because java's String.matches() checks the entire string, and not a substring (this is what I'm getting by reading the suggested answers)? – Raymond Arthur Aug 15 '23 at 13:23
  • Yes. The intuitive pattern would actually be `"(?i)[aeiou]+"` So `return string.matches("(?i)[aeiou]+");` – g00se Aug 15 '23 at 13:25
  • 1
    @azro so to understand your suggestion, `[b-df-hj-np-tv-z].*` means "find any character in the string that is in the Character Class"? I tried this regex and it worked :-) – Raymond Arthur Aug 15 '23 at 14:00

0 Answers0