正则表达式匹配
来源:互联网 发布:金税三期软件客服电话 编辑:程序博客网 时间:2024/06/06 03:03
请实现一个函数用来匹配包括'.'和'*'的正则表达式。模式中的字符'.'表示任意一个字符,而'*'表示它前面的字符可以出现任意次(包含0次)。 在本题中,匹配是指字符串的所有字符匹配整个模式。例如,字符串"aaa"与模式"a.a"和"ab*ac*a"匹配,但是与"aa.a"和"ab*a"均不匹配
public class Solution { public boolean match(char[] str, char[] pattern) { //条件判断 if(str==null||pattern==null){ return false; } return matchCore(str,0,pattern,0); } private boolean matchCore(char[] str,int strIndex,char[] pattern,int pIndex){ //有效性检验 //str和pattern同时到达尾部,完成匹配,返回true if(strIndex==str.length&&pIndex==pattern.length){ return true; } //str不到尾,pattern到尾部,返回false if(strIndex!=str.length&&pIndex==pattern.length){ return false; } //模式第2个是*,且字符串第1个跟模式第1个匹配,分3种匹配模式;如不匹配,模式后移2位 if (pIndex + 1 < pattern.length && pattern[pIndex + 1] == '*') { if(strIndex!=str.length&&str[strIndex]==pattern[pIndex]||strIndex!=str.length&&pattern[pIndex]=='.'){ //1.模式串后后移两位,相当于第一个匹配的字符被忽略掉,从字符串的下一个字符继续开始匹配 //2.字符串后移一位,模式串后移两位,相当于模式匹配一个字符 //3.字符串后移一位,模式串不动,因为模式串的第二个字符'*‘,可以匹配前面出现的多个字符 return matchCore(str,strIndex,pattern,pIndex+2)||matchCore(str,strIndex+1,pattern,pIndex+2)|| matchCore(str,strIndex+1,pattern,pIndex); }else{ return matchCore(str,strIndex,pattern,pIndex+2); } } //模式串第二个字符不是'*',并且两个串的第一个字符是匹配的 if(strIndex!=str.length&&str[strIndex]==pattern[pIndex]||strIndex!=str.length&&pattern[pIndex]=='.'){ return matchCore(str,strIndex+1,pattern,pIndex+1); //否则,直接返回false }else{ return false; } }}
阅读全文
0 0
- 正则表达式字符匹配
- 正则表达式 匹配"<"方法!
- 正则表达式匹配规则
- 正则表达式匹配规则
- 正则表达式最小匹配
- 正则表达式匹配字符串
- 正则表达式匹配
- 正则表达式匹配汉字
- 正则表达式匹配规则
- 正则表达式匹配关键字
- 正则表达式多次匹配
- 正则表达式匹配
- 正则表达式匹配汇总
- java:正则表达式匹配
- 正则表达式匹配居民身份证
- 正则表达式匹配次
- 匹配的正则表达式
- 正则表达式匹配
- 【esp8266】从0开始玩转Gokit3 SOC(3)全彩智能灯应用-编译固件
- Spring Cloud构建微服务架构-Hystrix服务降级
- 黑马商城项目_布局_主页、分类页、购物车页
- 四五十岁之后,还在编程的程序员都有谁?个个大师级
- 更好的webAPP
- 正则表达式匹配
- php连接mongoDB的几个问题
- 反向代理haproxy用法详解
- sql中cast()函数和convert()函数
- 程序员在35岁后应该转做管理?69岁的老程序员说不!
- 关于安卓调用wcf传递复杂参数的问题
- Android Studio多项目共享Library
- High Five
- Linux的脚本.sh