简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM