Look at this program:
Pattern p = Pattern.compile("hello");
Matcher m = p.matcher("[a-z]");
System.out.println(m.hitEnd()); // prints false
System.out.println(m.find()); // prints false
System.out.println(m.hitEnd()); // prints true
Notice, the first call of m.hitEnd() returns false. Look at JavaDoc, it says:
Returns true if the end of input was hit by the search engine in the
last match operation performed by this matcher.
Here it returns false, because it is called before the call of m.find(), so the matcher hasn't performed any match operations, yet. After the call of m.find() it returns true (because find() consumes the complete input string and hits the end). The meaning of that is also explained in JavaDoc:
When this method returns true, then it is possible that more input
would have changed the result of the last search.
When this returns true, it means the matcher hit the end of the input. In this case, hit means reached, not matched. (The input was completely consumed by the matcher).
EDIT
I hope it is wanted by you, that [a-z] is the input string for your regular expression hello, and it's not the other way around. If you had
Pattern p = Pattern.compile("[a-z]"); // The regex needs to be compiled.
Matcher m = p.matcher("hello"); // The input is given to the matcher
while (m.find()) { // In this case, returns true 5 times
System.out.println(m.group() + ", ");
}
your output would be
h, e, l, l, o,
hitEnd()method works, which can be confusing. See my answer for details.hello, and the input string is[a-z]. Because[a-z]looks like a regular expression, andhellolike a input string.