1.兩者差異:
find()方法是部分匹配,是查找輸入串中與模式匹配的子串,如果該匹配的串有組還可以使用group()函數。
matches()是全部匹配,是將整個輸入串與模式匹配,如果要驗證一個輸入的數據是否為數字類型或其他類型,一般要用matches()。
2.詳解:
matches
public static boolean matches(String regex, CharSequence input)
編譯給定正則表達式並嘗試將給定輸入與其匹配。
調用此便捷方法的形式
Pattern.matches(regex, input);
Pattern.compile(regex).matcher(input).matches() ;
如果要多次使用一種模式,編譯一次后重用此模式比每次都調用此方法效率更高。
參數:
regex - 要編譯的表達式
input - 要匹配的字符序列
拋出:
PatternSyntaxException - 如果表達式的語法無效
find
public boolean find()嘗試查找與該模式匹配的輸入序列的下一個子序列。
此方法從匹配器區域的開頭開始,如果該方法的前一次調用成功了並且從那時開始匹配器沒有被重置,則從以前匹配操作沒有匹配的第一個字符開始。
如果匹配成功,則可以通過 start、end 和 group 方法獲取更多信息。
matcher.start() 返回匹配到的子字符串在字符串中的索引位置.
matcher.end()返回匹配到的子字符串的最后一個字符在字符串中的索引位置.
matcher.group()返回匹配到的子字符串
返回:
當且僅當輸入序列的子序列匹配此匹配器的模式時才返回 true。
4.部分JAVA正則表達式示例
①字符匹配
Pattern p = Pattern.compile(expression); // 正則表達式
Matcher m = p.matcher(str); // 操作的字符串
boolean b = m.matches(); //返回是否匹配的結果
System.out.println(b);
Pattern p = Pattern.compile(expression); // 正則表達式
Matcher m = p.matcher(str); // 操作的字符串
boolean b = m. lookingAt (); //返回是否匹配的結果
System.out.println(b);
Pattern p = Pattern.compile(expression); // 正則表達式
Matcher m = p.matcher(str); // 操作的字符串
boolean b = m.find (); //返回是否匹配的結果
System.out.println(b);
②分割字符串
Pattern pattern = Pattern.compile(expression); //正則表達式
String[] strs = pattern.split(str); //操作字符串 得到返回的字符串數組
③替換字符串
Pattern p = Pattern.compile(expression); // 正則表達式
Matcher m = p.matcher(text); // 操作的字符串
String s = m.replaceAll(str); //替換后的字符串
④查找替換指定字符串
Pattern p = Pattern.compile(expression); // 正則表達式
Matcher m = p.matcher(text); // 操作的字符串
StringBuffer sb = new StringBuffer();
int i = 0;
while (m.find()) {
m.appendReplacement(sb, str);
i++; //字符串出現次數
}
m.appendTail(sb);//從截取點將后面的字符串接上
String s = sb.toString();
⑤查找輸出字符串
Pattern p = Pattern.compile(expression); // 正則表達式
Matcher m = p.matcher(text); // 操作的字符串
while (m.find()) {
matcher.start() ;
matcher.end();
matcher.group(1);
}
如果覺得上述內容還可以的話,可以掃描下方二維碼進行贊賞喲~👇👇👇
同時也可關注微信公眾號獲得更多個人分享~👇👇👇