tags:

views:

91

answers:

5

Why this code would fail?

assertTrue(Pattern.matches("[^a-zA-Z0-9]", "abc;"));
+3  A: 

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?

Tim Pietzcker
+1  A: 

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.

Amber
A: 

try "^[a-zA-Z0-9]" as pattern

SmokeIT
I believe the OP is trying to match the `;` in the target string. So it's not the regex that's wrong, it's using `matches()` instead of `find()`, as others have pointed out. In any case, "try this instead" is not a particularly helpful answer.
Alan Moore
A: 

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]

Valentin Rocher
+2  A: 

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.

rsp
It will assert true, by matching the `";"`, but I suspect that is not what the OP had in mind.
finnw
Yes, that's what I mean. What about if I use Pattern.matches(".*[^a-zA-Z0-9].*", "abc;")? Is it the same?
jackysee
@jackysee, It would result in the same behaviour, the difference is that between finding a non-alphanumeric and checking that a string has the format "anything" "non-alphanumeric" "anything" which is not quite the same. Using the find, you could look for the next non-alpha character in your string, using matches you cannot do that for instance.
rsp