Skip to content

Instantly share code, notes, and snippets.

@sontx
Created April 10, 2016 07:46
Show Gist options
  • Save sontx/9695ebdc83e2d61464ccfcc8f676782a to your computer and use it in GitHub Desktop.
Save sontx/9695ebdc83e2d61464ccfcc8f676782a to your computer and use it in GitHub Desktop.
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public final class WildcardMatcher {
private static final Pattern regex = Pattern.compile("[^*?]+|(\\*)|(\\?)");
private final Pattern escapeRegex;
private String getEscapeExpression(String expression) {
Matcher matcher = regex.matcher(expression);
StringBuffer buffer = new StringBuffer();
while (matcher.find()) {
if (matcher.group(1) != null)
matcher.appendReplacement(buffer, ".*");
else if (matcher.group(2) != null)
matcher.appendReplacement(buffer, ".");
else
matcher.appendReplacement(buffer, "\\\\Q" + matcher.group(0) + "\\\\E");
}
matcher.appendTail(buffer);
return buffer.toString();
}
public boolean matches(String st) {
return escapeRegex.matcher(st).matches();
}
public WildcardMatcher(String expression) {
String escapeExression = getEscapeExpression(expression);
escapeRegex = Pattern.compile(escapeExression);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment