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 goin开发者_如何学编程g wrong?
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.
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).
I think it should be a[1].matches("[a-zA-Z]*")
[a-zA-Z]
would only accept a single letter. You probably need [a-zA-Z]*
.
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]*")
a[1].matches("[a-zA-Z\\s]+")
may help
This expression should work for checking whether a string contains all alphabet or not.
a[1].matches("^[a-zA-Z]*$")
精彩评论