Michael
Michael

Reputation: 6172

Java string.matches() returns wrong statement

I'm running some code through the eclipse debugger and a[1].matches("[a-zA-Z]") is not equating to true when a[1] = "ABCD" (a is a string array).

I've read the javadoc on matches and [a-zA-Z] should be a valid regular expression..

Anyone know where I'm going wrong?

Upvotes: 4

Views: 6072

Answers (7)

rakibul sadik
rakibul sadik

Reputation: 21

This expression should work for checking whether a string contains all alphabet or not.

a[1].matches("^[a-zA-Z]*$")

Upvotes: 0

Alexander
Alexander

Reputation: 47

a[1].matches("[a-zA-Z\\s]+")  

may help

Upvotes: 0

Rob Hruska
Rob Hruska

Reputation: 120316

Try using this expression: [a-zA-Z]* (will match zero or more characters).

If you require at least one character, use: [a-zA-Z]+

The expression you're using will only match a single alpha character since it's not quantified.

Upvotes: 6

Paul Sasik
Paul Sasik

Reputation: 81499

The reason that you're not matching that is string is that your RegEx expression is trying to match just a single character. Try this:

a[1].matches("[a-zA-Z]*")

Upvotes: 0

JJ.
JJ.

Reputation: 5475

Try a[1].matches("[a-zA-Z]+"). It says "one or more characters" must match instead of only a single character.

Note that '*' instead of '+' matches "zero or more characters' so it will match empty String (probably not what you want).

Upvotes: 2

Eran Zimmerman Gonen
Eran Zimmerman Gonen

Reputation: 4507

[a-zA-Z] would only accept a single letter. You probably need [a-zA-Z]*.

Upvotes: 0

MByD
MByD

Reputation: 137382

I think it should be a[1].matches("[a-zA-Z]*")

Upvotes: 1

Related Questions