Skip to content

Instantly share code, notes, and snippets.

@subchen
Created November 25, 2013 07:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save subchen/7637744 to your computer and use it in GitHub Desktop.
Save subchen/7637744 to your computer and use it in GitHub Desktop.
Convert wildcard pattern to regular expression to match strings
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;
}
}
@ArashPartow
Copy link

A detailed explanation of wildcard pattern matching and general globbing can be found here:

https://www.partow.net/programming/wildcardmatching/index.html

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment