Untitled

mail@pastecode.io avatar
unknown
plain_text
a year ago
1.9 kB
2
Indexable
    public static boolean contains(String string, String pattern) {

        if (isNull(string) || isNull(pattern) || pattern.length() > string.length()) {
            return false;
        }
        if (pattern.isEmpty()) {
            return true;
        }
        return match(string, pattern, 0, 0);
    }

    private static boolean match(String string, String pattern, int sIndex, int pIndex) {
        int sLength = string.length();
        int pLength = pattern.length();

        while (sIndex < sLength && pIndex < pLength) {
            char sChar = string.charAt(sIndex);
            char pChar = pattern.charAt(pIndex);

            if (pChar == '*') {
                // Handle the wildcard by trying to match 0 or more characters in the string.
                if (pIndex + 1 < pLength && pattern.charAt(pIndex + 1) == '\\') {
                    // Escaped asterisk, treat it as a regular character
                    pIndex++;
                } else {
                    for (int i = sIndex; i <= sLength; i++) {
                        if (match(string, pattern, i, pIndex + 1)) {
                            return true;
                        }
                    }
                    return false;
                }
            } else if (pChar == '\\') {
                // Check if the next character is an escaped asterisk
                if (pIndex + 1 < pLength && pattern.charAt(pIndex + 1) == '*') {
                    // Treat the backslash as a regular character and skip it
                    pIndex++;
                }
            } else if (sChar != pChar) {
                return false;
            }

            sIndex++;
            pIndex++;
        }
        // If we have reached the end of both string and pattern, it's a match.
//        return sIndex == sLength && pIndex == pLength;
        return pIndex == pLength;
    }