且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

确定两个字符串是否匹配的递归方法.匹配过程应该允许“通配符".一个“@"和一个“*"

更新时间:2023-02-19 23:41:15

看看这个.第一个想法,可以改进.

Take a look at this. A first idea, could be improved.

public static boolean match(String regex, String input) {
    return match(regex.toCharArray(), input.toCharArray(), regex.length() - 1, input.length() - 1);
}

private static boolean match(char[] regex, char[] input, int regexPosition, int inputPosition) {
    if (regexPosition < 0 || inputPosition < 0) {
        return false;
    }
    if (regexPosition == 0 && inputPosition == 0) {
        return true;
    }
    if (regex[regexPosition] == input[inputPosition] || regex[regexPosition] == '@') {
        return match(regex, input, regexPosition - 1, inputPosition - 1);
    }
    if (regex[regexPosition] == '*') {
        if (regex[regexPosition - 1] == '@') {
            /* @* => @ matter of taste. Sure there are counter examples. */
            return match(regex, input, regexPosition - 2, inputPosition - 1);
        }
        final int newInputPosition = String.valueOf(input).lastIndexOf(regex[regexPosition - 1]);
        if (newInputPosition >= 0) {
            return match(regex, input, regexPosition - 1, newInputPosition);
        }
    }
    return false;
}