今天在判斷字符串是否存在某個字符串,直接用String.matches(regex),死活匹配不出來,在線正則工具用了很多都是可以的,后面找到問題,總結一下,防止再次踩坑。
一、前提
java中判斷一段字符串中是否包含某個字符串的方式:
1、
String.matches(regex);
閱讀源碼發現,這個方法本質是調用了Pattern.matches(regex, str)
,而該方法調Pattern.compile(regex).matcher(input).matches()
方法,而Matcher.matches()
方法試圖將整個區域與模式匹配,如果匹配成功,則可以通過開始、結束和組方法獲得更多信息。
即這個方法會在表達式前后加上$(regex$),是對這個字符串全匹配
而不會只匹配其中的子串,如果只想匹配子串,則需要表達式匹配整段
2、
Pattern.compile(regex).matcher(str).find()
Matcher.find()
方法則是僅僅進行匹配字串的方法
如果不想使用全局匹配則可以使用Matcher.find()
方法
二、附源碼
1、String.matches(regex)
String.matches(regex)
public boolean matches(String regex) {
return Pattern.matches(regex, this);
}
Pattern.matches(regex, this)
public static boolean matches(String regex, CharSequence input) {
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(input);
return m.matches();
}
2、Matcher.find()
Pattern.compile
public static Pattern compile(String regex) {
return new Pattern(regex, 0);
}
Pattern.matcher
public Matcher matcher(CharSequence input) {
if (!compiled) {
synchronized(this) {
if (!compiled)
compile();
}
}
Matcher m = new Matcher(this, input);
return m;
}
Matcher.find()
public boolean find() {
int nextSearchIndex = last;
if (nextSearchIndex == first)
nextSearchIndex++;
// If next search starts before region, start it at region
if (nextSearchIndex < from)
nextSearchIndex = from;
// If next search starts beyond region then it fails
if (nextSearchIndex > to) {
for (int i = 0; i < groups.length; i++)
groups[i] = -1;
return false;
}
return search(nextSearchIndex);
}
三、總結
各個匹配的優缺點都有,大家可以按需選擇
如果僅僅只需要獲取字符串中是否包含某個字符串,還是用Matcher.find()比較方便