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
您的點贊和關注是對我最大的支持,謝謝!