java正則表示式匹配
阿新 • • 發佈:2019-02-11
package offer;
/*
* 字串匹配
* "."匹配任意一個字元
* "*"表示前面的字元出現任意次
*/
public class Match {
public static void main(String[] args) {
String str = "aaa";
String pattern = "b*aaaa*a*a*a*.*";
System.out.println(match(str, 0, pattern, 0));
}
private static boolean match(String str , int strIndex, String pattern, int patternIndex) {
//出口1 :兩個字串都到達了結尾,說明匹配成功,返回true
if (strIndex >= str.length() && patternIndex >= pattern.length()) {
return true;
}
//出口2 :模式串達到了結尾,說明匹配失敗,返回false
if (strIndex != str.length() && patternIndex >= pattern.length()) {
return false;
}
//若下一個字元為'*'
if (patternIndex + 1 < pattern.length() && pattern.charAt(patternIndex + 1) == '*') {
if(strIndex >= str.length()){
//若匹配串已經結束
return match(str, strIndex, pattern, patternIndex + 2);
} else {
if (str.charAt(strIndex) == pattern.charAt(patternIndex) || (pattern.charAt(patternIndex) == '.' && strIndex != str.length()) ) {
return match(str, strIndex, pattern, patternIndex + 2)
||match(str, strIndex + 1, pattern, patternIndex + 2)
||match(str, strIndex + 1, pattern, patternIndex);
} else {
return match(str, strIndex, pattern, patternIndex + 2);
}
}
}
//若當前字元為'.'
if(strIndex >= str.length()){
//若匹配串已經結束
return false;
} else{
if (str.charAt(strIndex) == pattern.charAt(patternIndex) || pattern.charAt(patternIndex) == '.') {
return match(str, strIndex + 1, pattern, patternIndex + 1);
}
}
return false;
}
}