Java Wildcard to Regex wildcardToRegex(String wildcard)

Here you can find the source of wildcardToRegex(String wildcard)

Description

Converts given string containing wildcards (* or ?) to its corresponding regular expression.

License

Apache License

Parameter

Parameter Description
wildcard the string

Return

the regular expression

Declaration

private static String wildcardToRegex(String wildcard) 

Method Source Code

//package com.java2s;
//License from project: Apache License 

public class Main {
    /**//from   www .ja v  a2s  .  co m
     * Converts given string containing wildcards (* or ?) to its corresponding regular expression.
     * 
     * @param wildcard the string
     * @return the regular expression
     */
    private static String wildcardToRegex(String wildcard) {
        StringBuffer s = new StringBuffer(wildcard.length());
        s.append('^');
        for (int i = 0, is = wildcard.length(); i < is; i++) {
            char c = wildcard.charAt(i);
            switch (c) {
            case '*':
                s.append(".*");
                break;
            case '?':
                s.append(".");
                break;
            // escape special regexp-characters
            case '(':
            case ')':
            case '[':
            case ']':
            case '$':
            case '^':
            case '.':
            case '{':
            case '}':
            case '|':
            case '\\':
                s.append("\\");
                s.append(c);
                break;
            default:
                s.append(c);
                break;
            }
        }
        s.append('$');
        return (s.toString());
    }
}

Related

  1. wildcardToRegex(CharSequence s)
  2. wildcardToRegex(final String input)
  3. wildcardToRegex(final String pattern)
  4. wildcardToRegex(String toSearch, boolean supportSQLWildcard)
  5. wildcardToRegex(String wildcard)
  6. wildcardToRegex(String wildcardPattern)
  7. wildcardToRegexp(String globExp)
  8. wildcardToRegexString(String wildcard)