Created
April 10, 2016 07:46
-
-
Save sontx/9695ebdc83e2d61464ccfcc8f676782a to your computer and use it in GitHub Desktop.
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
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