正则表达式匹配(Java实现)

本文介绍了一种正则表达式匹配算法的实现,通过递归方式处理字符串和模式的匹配,特别关注了'*'通配符的特殊处理。算法能够处理包含'.', '*'等特殊字符的复杂正则表达式,提供了详细的代码示例和测试用例。

public class E19RegularExpression {
    //正则表达式匹配

    //每次只比较确定一个字符
    public static boolean isMatch(char[] str, char[] pattern){
        if (str == null || pattern == null)
            return false;
        return matchCore(str, pattern, 0, 0);
    }

    private static boolean matchCore(char[] str, char[] pattern,
                                     int sIndex, int pIndex){
        int sLength = str.length;
        int pLength = pattern.length;
        //递归终止条件
        if (sLength == sIndex && pIndex == pLength)
            return true;
        //模式还未结束,字符串已结束仍有可能匹配成功,反之一定匹配失败
        if (pIndex == pLength && sIndex < sLength )
            return false;
        //防止下标越界
        if (pIndex < pLength - 1 && pattern[pIndex + 1] == '*'){
            if (sIndex != sLength  &&
                    (str[sIndex] == pattern[pIndex] || pattern[pIndex] == '.')){
                        //忽略*
                return matchCore(str, pattern, sIndex, pIndex + 2) ||
                        //采用该次*,并向前推近
                       matchCore(str, pattern, sIndex + 1, pIndex + 2)||
                        //采用该次*,并打算继续采用
                       matchCore(str, pattern, sIndex + 1, pIndex);
            }
            else
                return matchCore(str, pattern, sIndex, pIndex + 2);
        }

        if (sIndex != sLength  &&
                (str[sIndex] == pattern[pIndex] || pattern[pIndex] == '.'))
                    //同时推进
            return matchCore(str, pattern, sIndex + 1, pIndex + 1);

        return false;
    }

    //测试用例
    public static void main(String[] args){
        char[] str = {'a', 'b', 'b', 'b'};
        char[] pattern = {'.', 'b', '*', 'a', '*', 'c', '*'};
        System.out.print(E19RegularExpression.isMatch(str, pattern));
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值