Simple java regexp problem
Why 开发者_运维问答this code would fail?
assertTrue(Pattern.matches("[^a-zA-Z0-9]", "abc;"));
Because the .matches()
method tries to match the entire string, and your regex doesn't match the entire string, only the semicolon. The Matcher.find()
method would work (in this case: find a character that is not a letter between a and z nor a number between 0 and 9. Of course, it will also find á, ö etc.)
What is it you really want to do?
If fails because matches tries to match the complete string, your regexp matches 1 character which is not in the character ranges you list, if you change to:
assertTrue(Pattern.compile("[^a-zA-Z0-9]").matcher("abc;").find());
it should assert true.
Because Pattern.matches()
is equivalent to the corresponding pattern being compiled and fed to Matcher.matches()
which, as specified, checks to see if the entire input matches the pattern. If you only want to match part of the input, you'll want to use Matcher.find()
instead.
try "^[a-zA-Z0-9]" as pattern
Because when you put the ^ inside, it means any char not in a-z or A-Z. What you want is ^[a-zA-Z0-9]
精彩评论