[英]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: 使用matcher.find()
方法:
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: PS:如果您使用循环find
或多次find
,最好这样做:
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
. matches
尝试将整个输入与模式进行匹配,因此返回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
如果在此匹配器执行的最后一个匹配操作中搜索引擎命中了输入的结尾,则hitEnd
返回true
,因为不是,则返回false
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.