public class E19RegularExpression {
//正则表达式匹配
//每次只比较确定一个字符
public static boolean isMatch(char[] str, char[] pattern){
if (str == null || pattern == null)
return false;
return matchCore(str, pattern, 0, 0);
}
private static boolean matchCore(char[] str, char[] pattern,
int sIndex, int pIndex){
int sLength = str.length;
int pLength = pattern.length;
//递归终止条件
if (sLength == sIndex && pIndex == pLength)
return true;
//模式还未结束,字符串已结束仍有可能匹配成功,反之一定匹配失败
if (pIndex == pLength && sIndex < sLength )
return false;
//防止下标越界
if (pIndex < pLength - 1 && pattern[pIndex + 1] == '*'){
if (sIndex != sLength &&
(str[sIndex] == pattern[pIndex] || pattern[pIndex] == '.')){
//忽略*
return matchCore(str, pattern, sIndex, pIndex + 2) ||
//采用该次*,并向前推近
matchCore(str, pattern, sIndex + 1, pIndex + 2)||
//采用该次*,并打算继续采用
matchCore(str, pattern, sIndex + 1, pIndex);
}
else
return matchCore(str, pattern, sIndex, pIndex + 2);
}
if (sIndex != sLength &&
(str[sIndex] == pattern[pIndex] || pattern[pIndex] == '.'))
//同时推进
return matchCore(str, pattern, sIndex + 1, pIndex + 1);
return false;
}
//测试用例
public static void main(String[] args){
char[] str = {'a', 'b', 'b', 'b'};
char[] pattern = {'.', 'b', '*', 'a', '*', 'c', '*'};
System.out.print(E19RegularExpression.isMatch(str, pattern));
}
}
正则表达式匹配(Java实现)
最新推荐文章于 2023-04-04 14:05:33 发布