javaregexstring

Partial match for regular expression in Java


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.


Solution

  • 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: