java正则表达式匹配

package offer;
/*
 * 字符串匹配
 * "."匹配任意一个字符
 * "*"表示前面的字符出现任意次
 */
public class Match {
    public static void main(String[] args) {
        String str = "aaa";
        String pattern = "b*aaaa*a*a*a*.*";
        System.out.println(match(str, 0, pattern, 0));
    }

    private static boolean match(String str, int strIndex, String pattern, int patternIndex) {
        //出口1 :两个字符串都到达了结尾,说明匹配成功,返回true
        if (strIndex >= str.length() && patternIndex >= pattern.length()) {
            return true;
        }
        //出口2 :模式串达到了结尾,说明匹配失败,返回false
        if (strIndex != str.length() && patternIndex >= pattern.length()) {
            return false;
        }

        //若下一个字符为'*'
        if (patternIndex + 1 < pattern.length() && pattern.charAt(patternIndex + 1) == '*') {
            if(strIndex >= str.length()){  
                //若匹配串已经结束  
                return match(str, strIndex, pattern, patternIndex + 2);
            } else {
                if (str.charAt(strIndex) == pattern.charAt(patternIndex) || (pattern.charAt(patternIndex) == '.' && strIndex != str.length()) ) {
                    return match(str, strIndex, pattern, patternIndex + 2)
                            ||match(str, strIndex + 1, pattern, patternIndex + 2)
                            ||match(str, strIndex + 1, pattern, patternIndex);
                } else {
                    return match(str, strIndex, pattern, patternIndex + 2);
                }
            }
        }

        //若当前字符为'.'
        if(strIndex >= str.length()){ 
            //若匹配串已经结束  
            return false;
        } else{
            if (str.charAt(strIndex) == pattern.charAt(patternIndex) || pattern.charAt(patternIndex) == '.') {
                return match(str, strIndex + 1, pattern, patternIndex + 1);
            }
        }

        return false;
    }
}

你可能感兴趣的:(数据结构与算法)