Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular expression for obtaining a vowel occurrence in Java?

Tags:

java

regex

text

For coding an ID generator, I got to obtain the first vowel appearance ignoring first letter in a lastname.

I coded:

public static Character primeraVocal(String apellido) {

    for (Character c : apellido.toUpperCase().substring(1).toCharArray()) {
        if (c.equals('A') || c.equals('E') || c.equals('I') || c.equals('O') || c.equals('U'))
            return c;
    }

    return '!';
}

However I know this would be sort of one line of code using a regex. How would it look like?

like image 758
diegoaguilar Avatar asked Mar 31 '14 15:03

diegoaguilar


1 Answers

As you want to ignore the first letter, this code will help you get there.

    Pattern pattern = Pattern.compile("[\\w]([aeiouâãäåæçèéêëìíîïðñòóôõøùúûü])", Pattern.CASE_INSENSITIVE);
    Matcher matcher = pattern.matcher("Aguilar");
    if (matcher.find()) {
        return String.valueOf(matcher.group(1));
    }

You can also use this method in order to normalize your returned String. So when you get an accented vowel, you can use the normalized value to create your ID....

public static String unAccent(String s) {
    //http://www.rgagnon.com/javadetails/java-0456.html
    String temp = Normalizer.normalize(s, Normalizer.Form.NFD);
    Pattern pattern = Pattern.compile("\\p{InCombiningDiacriticalMarks}+");
    return pattern.matcher(temp).replaceAll("");
}

Please see the working example here... https://ideone.com/gaGbtF

like image 157
Garis M Suero Avatar answered Oct 04 '22 10:10

Garis M Suero