Created
November 25, 2013 07:38
-
-
Save subchen/7637744 to your computer and use it in GitHub Desktop.
Convert wildcard pattern to regular expression to match strings
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public final class WildCharUtils { | |
private static final char ESCAPES[] = { '$', '^', '[', ']', '(', ')', '{', '|', '+', '\\', '.', '<', '>' }; | |
private final String regexp; | |
public static Pattern compile(String pattern) { | |
return new Pattern(pattern); | |
} | |
private Pattern(String pattern) { | |
regexp = wildcardToRegexp(pattern); | |
} | |
public boolean match(String input) { | |
if (input == null) { | |
return false; | |
} | |
return input.matches(this.regexp); | |
} | |
private String wildcaldToRegexp(String pattern) { | |
String result = "^"; | |
for (int i = 0; i < pattern.length(); i++) { | |
char ch = pattern.charAt(i); | |
boolean escaped = false; | |
for (int j = 0; j < ESCAPES.length; j++) { | |
if (ch == ESCAPES[j]) { | |
result += "\\" + ch; | |
escaped = true; | |
break; | |
} | |
} | |
if (!escaped) { | |
if (ch == '*') { | |
result += ".*"; | |
} else if (ch == '?') { | |
result += "."; | |
} else { | |
result += ch; | |
} | |
} | |
} | |
result += "$"; | |
return result; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
A detailed explanation of wildcard pattern matching and general globbing can be found here:
https://www.partow.net/programming/wildcardmatching/index.html