public class Solution {
//(1)调用库函数
public boolean match(char[] str,char[] pattern)
{
return new String(str).matches(new String(pattern));
}
//(2)[正规匹配方式]
public boolean match2(char[] str,char[] pattern) {
if (str == null || pattern == null) {
return false;
}
int strIndex = 0;
int patternIndex = 0;
return matchCore(str,strIndex,pattern,patternIndex);
}
public boolean matchCore(char[] str,int strIndex,char[] pattern,int patternIndex) {
//有效性检验:str到尾,pattern到尾,匹配成功
if (strIndex == str.length && patternIndex == pattern.length) {
return true;
}
//pattern先到尾,匹配失败
if (strIndex != str.length && patternIndex == pattern.length) {
return false;
}
//模式第2个是*,且字符串第1个跟模式第1个匹配,分3种匹配模式;如不匹配,模式后移2位
if (patternIndex + 1 < pattern.length && pattern[patternIndex + 1] == '*') {
if ((strIndex != str.length && pattern[patternIndex] == str[strIndex]) || (pattern[patternIndex] == '.' && strIndex != str.length)) {
return matchCore(str,patternIndex + 2)//模式后移2,视为x*匹配0个字符
|| matchCore(str,strIndex + 1,patternIndex + 2)//视为模式匹配1个字符
|| matchCore(str,patternIndex);//*匹配1个,再匹配str中的下一个
} else {
return matchCore(str,patternIndex + 2);
}
}
//模式第2个不是*,且字符串第1个跟模式第1个匹配,则都后移1位,否则直接返回false
if ((strIndex != str.length && pattern[patternIndex] == str[strIndex]) || (pattern[patternIndex] == '.' && strIndex != str.length)) {
return matchCore(str,patternIndex + 1);
}
return false;
}
}
原文地址:https://www.jb51.cc/regex/357485.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。