[英]Java regex, matches and find
我仍然在理解match()和find()的區別方面仍然遇到問題,這里的代碼
final Matcher subMatcher = Pattern.compile("\\d+").matcher("123");
System.out.println("Found : " + subMatcher.matches());
System.out.println("Found : " + subMatcher.find());
輸出是
Found : true Found : false
什么我了解比賽,從這個找到答案 ,是匹配()試圖同時查找()只嘗試匹配下一個匹配的字符串整個字符串匹配,並且匹配增添了^和$元字符開始和如果我們沒有多次使用它,則begin和find()可以有不同的結果,但是這里123仍然是一個子字符串,第二個輸出應該為true。 如果我注釋掉第二行,則確實顯示輸出為true
當您調用matches()
, Matcher
已經搜索到匹配項(整個String
)。 調用find
Matcher
將在當前匹配之后嘗試再次查找模式,但是由於匹配整個String
的匹配之后沒有剩余字符,因此find
返回false
。
要再次搜索String
,您需要創建一個新的Matcher
或調用reset()
:
final Matcher subMatcher = Pattern.compile("\\d+").matcher("123");
System.out.println("Found : " + subMatcher.matches());
subMatcher.reset();
System.out.println("Found : " + subMatcher.find());
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.