The fool doth think he is wise, but the wise man knows himself to be a fool.
愚者总自觉得聪明,智者则有自知之明。
智者千虑,必有一失;愚者千虑,必有一得。在不少文本编辑器里,正则表达式一般被用来检索、替换那些匹配某个模式的文本。正则表达式也是先后端通吃,百无禁忌。git
正则表达式中,最重要的就是通配符。用到的思想仍是回溯算法。github
在这里作了一个简易版的正则表达式实现。只包含两种通配符:正则表达式
全部源码均已上传至github:连接算法
/**
* 标识
*/
private boolean match;
/**
* 正则表达式
*/
private char[] patChars;
/**
* 长度
*/
private int plen;
/**
* 初始化
*
* @param patten 正则表达式
*/
private Pattern(String patten) {
patChars = patten.toCharArray();
this.plen = patChars.length;
match = false;
}复制代码
private boolean isMatch(String txt) {
match = false;
char[] txtChars = txt.toCharArray();
int tlen = txtChars.length;
recursiveMatch(0, 0, txtChars, tlen);
return match;
}复制代码
这里其实就是一个大型的if-else,判断符合哪种状况,而后进行递归。若是再加几种状况,也就是多加一个if-else,这样的话if-else嵌套层级太多,能够考虑使用switch或者使用设计模式,这是后话,暂且不提。后端
private void recursiveMatch(int ti, int pj, char[] txtChars, int tlen) {
if (match) return;
if (pj == plen) {
if (ti == tlen) match = true;
return;
}
if (patChars[pj] == '*') {//* 任意字符
for (int i = 0; i < tlen - ti; i++) {
recursiveMatch(ti + i, pj + 1, txtChars, tlen);
}
} else if (patChars[pj] == '?') {//? 0 or 1
recursiveMatch(ti, pj + 1, txtChars, tlen);
recursiveMatch(ti + 1, pj + 1, txtChars, tlen);
} else if (ti < tlen && patChars[pj] == txtChars[ti]) {
recursiveMatch(ti + 1, pj + 1, txtChars, tlen);
}
}复制代码
public static void main(String[] args) {
String patten = "*@c?.com";
Pattern pattern = new Pattern(patten);
String txtT = "666@cc.com";
boolean resT = pattern.isMatch(txtT);
System.out.println(txtT + "的匹配结果:" + resT);
String txtF = "666@c.con";
boolean resF = pattern.isMatch(txtF);
System.out.println(txtF + "的匹配结果:" + resF);
}复制代码
匹配网站设计模式
其余:传送门bash
您的点赞和关注是对我最大的支持,谢谢!