Skip to content
Advertisement

Regex doesn’t work in String.matches()

I have this small piece of code

String[] words = {"{apf","hum_","dkoe","12f"};
for(String s:words)
{
    if(s.matches("[a-z]"))
    {
        System.out.println(s);
    }
}

Supposed to print

dkoe

but it prints nothing!!

Advertisement

Answer

Welcome to Java’s misnamed .matches() method… It tries and matches ALL the input. Unfortunately, other languages have followed suit 🙁

If you want to see if the regex matches an input text, use a Pattern, a Matcher and the .find() method of the matcher:

Pattern p = Pattern.compile("[a-z]");
Matcher m = p.matcher(inputstring);
if (m.find())
    // match

If what you want is indeed to see if an input only has lowercase letters, you can use .matches(), but you need to match one or more characters: append a + to your character class, as in [a-z]+. Or use ^[a-z]+$ and .find().

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement