Java Wildcard Match wildCardMatch(String text, String wildcard)

Here you can find the source of wildCardMatch(String text, String wildcard)

Description

Performs a WildCard matching for the text and pattern provided.

License

Open Source License

Parameter

Parameter Description
text The text to be tested for matches.
wildcard The pattern to be matched for. This can contain the WildCard character '*' (asterisk).

Return

true if a match is found, false otherwise.

Declaration

public static boolean wildCardMatch(String text, String wildcard) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

public class Main {
    /**// w  w w. j  a v a2  s .c  o  m
     * Performs a WildCard matching for the text and pattern provided.
     * 
     * @param text
     *          The text to be tested for matches.
     * @param wildcard
     *          The pattern to be matched for. This can contain the WildCard character '*' (asterisk).
     * @return <tt>true</tt> if a match is found, <tt>false</tt> otherwise.
     * @see #wildCardMatchIgnoreCase(String, String)
     */
    public static boolean wildCardMatch(String text, String wildcard) {
        if (wildcard == null || text == null) {
            return wildcard == null && text == null;
        }
        return text.matches(wildcardToRegex(wildcard));
    }

    /**
     * Converts the provided WildCard text to a Regular Expression.
     * 
     * @param wildcard
     *          Text to convert.
     * @return The converted WildCard text.
     */
    public static String wildcardToRegex(String wildcard) {
        String retObj = "^";
        if (wildcard != null) {
            for (int i = 0, is = wildcard.length(); i < is; i++) {
                char c = wildcard.charAt(i);
                switch (c) {
                case '*':
                    retObj += ".*";
                    break;
                case '?':
                    retObj += ".";
                    break;
                case '(':
                case ')':
                case '[':
                case ']':
                case '$':
                case '^':
                case '.':
                case '{':
                case '}':
                case '|':
                case '\\':
                    // escape special RegExp chars
                    retObj += "\\" + c;
                    break;
                default:
                    retObj += c;
                    break;
                }
            }
        }
        retObj += "$";
        return retObj;
    }
}

Related

  1. wildcardMatch(String string, String pattern)
  2. wildCardMatch(String text, String pattern)
  3. wildCardMatch(String text, String pattern)
  4. wildCardMatch(String text, String pattern)
  5. wildCardMatch(String text, String pattern)
  6. wildcardMatches(String pattern, String text)