Verify that the first letter is a vowel

1

I am trying to validate with a regular expression that the first letter is a vowel in the following way, but I can not.

        String pattern = "[aeiouAEIOU]{1}[A-Za-z]";
    String buscar = "alphabet";
    if (buscar.matches(pattern))
        System.out.println("T");
    else
        System.out.println("F");

I have also tried changing the string pattern to

String pattern = "\A[aeiouAEIOU]*";

any help?

    
asked by Roberto Gimenez 02.09.2018 в 13:40
source

3 answers

1
String pattern = "^[aeiouAEIOU]{1}[A-Za-z]*";
    
answered by 02.09.2018 / 17:32
source
4

You can use something like this:

/^[aeiou]{1}.*/i

Here is an explanation of what he does:

  • ^ : indicates the beginning of the chain. That way you make sure that the regular expression is going to search at the beginning only and not between means (if you do not put it, strings like "house" will be considered valid because they have a vowel in between).
  • [aeiou]{1} : specifies only one of the characters contained between the brackets. That is, one of the vowels: a , e , i , o , u .
  • .* : basically means "anything" (characters, symbols, numbers ...) If you want them to be only letters, you can use what you had in one of your tests: [a-zA-Z]* .
  • i : indicates that the string will be non-sensitive to the case, that is, it will also be case sensitive.

You can see this regular expression working in Regex101 .

In the case of Java, to indicate that it is not sensitive to the case, instead of putting the i at the end, you must put (?i) at the beginning, so the regular expression will work:

(?i)^[aeiou]{1}.*
    
answered by 02.09.2018 в 14:41
0

I was already desperate ... but I think I found it ...

String pattern="[a-uA-U] {1} [A-Za-z] *";

    
answered by 02.09.2018 в 13:42