java regex what the heck? am I misreading the regex docs completey?
java, regex
Solution
`String#matches()` tests `this` string against the entire pattern. Let's take a trip down JavaDoc lane:
String#matches(String)
Tells whether or not this string matches the given regular expression.
An invocation of this method of the form str`.matches`(regex) yields exactly the same result as the expression
`Pattern.matches`(regex, str)
so let's trace it through:
Pattern#matches(String regex, CharSequence input)
Compiles the given regular expression and attempts to match the given input against it.
An invocation of this convenience method of the form
Pattern.matches(regex, input);
behaves in exactly the same way as the expression
Pattern.compile(regex).matcher(input).matches()
One last step:
Matcher#matches()
Attempts to match the entire region against the pattern.
There you go. Not evident from the `String#matches(String)` JavaDoc, certainly. The solution is, of course, to use a method which does not insist on matching the pattern to the entire string.
Problem
``` System.out.println("a".matches("^[A-Za-z]+")); System.out.println("a ".matches("^[A-Za-z]+")); ``` This gives me: ``` true false ``` What the heck is up? As far as I am reading it, "[A-Za-z]" includes "a", and "+" means one or more, so this seems like it would work, at least in this universe.... Details are: Mac OS X 10.8.4 ``` $ java -version java version "1.6.0_51" Java(TM) SE Runtime Environment (build 1.6.0_51-b11-457-11M4509) Java HotSpot(TM) 64-Bit Server VM (build 20.51-b01-457, mixed mode) ``` Maybe I have been writing perl too long and java's regex system is kind of like it but not? No idea.