Reputation: 9506
How can I understand if a regex partially matches its subject?
I tried this:
Pattern.compile("^\\d").matcher("01L").hitEnd()
and this:
Pattern.compile("^\\d").matcher("01L").matches()
and they are both false, I want to test if the string starts with a digit.
Upvotes: 1
Views: 1281
Reputation: 784938
Use matcher.find()
method:
boolean valid = Pattern.compile("^\\d").matcher("01L").find(); //true
PS: If you're using find
in a loop or multiple times it is better to do:
Pattern p = Pattern.compile("^\\d"); // outside loop
boolean valid = p.matcher("01L").find(); // repeat calls
You are getting:
matches
attempts to match the entire input against the pattern hence it returns false
.hitEnd
returns true
if the end of input was hit by the search engine in the last match operation performed by this matcher and since it didn't you get false
Upvotes: 5