Alachisoft.NCache.Common.Util.WildcardEnabledRegex Maven / Gradle / Ivy
package Alachisoft.NCache.Common.Util;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class WildcardEnabledRegex {
private final Pattern pattern;
public WildcardEnabledRegex(String pattern) {
this.pattern = Pattern.compile(ConvertWildCard(pattern));
}
public static String WildcardToRegex(String pattern) {
return "^" + pattern.replace("\\*", ".*").replace("\\?", ".") + "$";
}
public static String ConvertWildCard(String pattern) {
StringBuilder myPattern = new StringBuilder(pattern);
String newPattern = pattern;
boolean esSeq = false;
boolean change = false;
ArrayList esChar = new ArrayList();
int pos, newPos = -1;
if (pattern.contains("\\")) {
for (int i = 0; i < pattern.length(); i++) {
pos = myPattern.indexOf("\\", newPos + 1);
if (pos > newPos) {
esChar.add(myPattern.charAt(pos + 1));
myPattern.deleteCharAt(pos + 1);
newPos = pos;
}
esSeq = true;
}
pattern = myPattern.toString();
}
if (pattern.contains("%")) {
newPattern = pattern.replaceAll("%", ".*");
change = true;
}
if (pattern.contains("_")) {
if (!change) {
newPattern = pattern.replaceAll("_", ".?");
} else {
newPattern = newPattern.replaceAll("_", ".?");
}
}
if (esSeq) {
newPos = -1;
myPattern = new StringBuilder(newPattern);
for (int i = 0; i < esChar.size(); i++) {
int pos1 = myPattern.indexOf("\\", newPos + 1);
if (pos1 > newPos) {
myPattern.insert(pos1 + 1, esChar.get(i).toString());
newPos = pos1;
}
}
newPattern = myPattern.toString();
}
return newPattern;
}
public final boolean IsMatch(String text) {
Matcher matcher = pattern.matcher(text);
return matcher.find();
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy