John Eipe
John Eipe

Reputation: 11228

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!!

Upvotes: 193

Views: 251208

Answers (9)

fge
fge

Reputation: 121710

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().

Upvotes: 415

MohsenB
MohsenB

Reputation: 1921

you must put at least a capture () in the pattern to match, and correct pattern like this:

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

Upvotes: -2

Shanta
Shanta

Reputation: 51

I have faced the same problem once:

Pattern ptr = Pattern.compile("^[a-zA-Z][\\']?[a-zA-Z\\s]+$");

The above failed!

Pattern ptr = Pattern.compile("(^[a-zA-Z][\\']?[a-zA-Z\\s]+$)");

The above worked with pattern within ( and ).

Upvotes: 5

Hachi
Hachi

Reputation: 3289

java's implementation of regexes try to match the whole string

that's different from perl regexes, which try to find a matching part

if you want to find a string with nothing but lower case characters, use the pattern [a-z]+

if you want to find a string containing at least one lower case character, use the pattern .*[a-z].*

Upvotes: 18

Anita Kulkarni
Anita Kulkarni

Reputation: 324

You can make your pattern case insensitive by doing:

Pattern p = Pattern.compile("[a-z]+", Pattern.CASE_INSENSITIVE);

Upvotes: -3

Boni
Boni

Reputation: 610

Used

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

Upvotes: 13

yshavit
yshavit

Reputation: 43391

String.matches returns whether the whole string matches the regex, not just any substring.

Upvotes: 34

user647772
user647772

Reputation:

Your regular expression [a-z] doesn't match dkoe since it only matches Strings of lenght 1. Use something like [a-z]+.

Upvotes: 2

dogbane
dogbane

Reputation: 274612

[a-z] matches a single char between a and z. So, if your string was just "d", for example, then it would have matched and been printed out.

You need to change your regex to [a-z]+ to match one or more chars.

Upvotes: 52

Related Questions