在我的应用程序中,我需要数字的过滤器概念。因此,我需要生成动态正则表达式格式。例如,如果给定输入,例如(attrN = number,operator =“ equal”,value = 459)和(attrN = number,operator =“小于等于”,值= 57)和(attrN =数字,operator =“不等于”,值= 45)和(attrN =数字,operator =“大于等于”,值= 1000)。基于上述条件需要开发动态正则表达式。我尝试了小于相等条件,但并没有得到大于等于条件的并和减法。我需要逻辑或算法。
public class NumericRangeRegex {
public String baseRange(String num, boolean up, boolean leading1) {
char c = num.charAt(0);
char low = up ? c : leading1 ? '1' : '0';
char high = up ? '9' : c;
if (num.length() == 1)
return charClass(low, high);
String re = c + "(" + baseRange(num.substring(1), up, false) + ")";
if (up) low++; else high--;
if (low <= high)
re += "|" + charClass(low, high) + nDigits(num.length() - 1);
return re;
}
private String charClass(char b, char e) {
return String.format(b==e ? "%c" : e-b>1 ? "[%c-%c]" : "[%c%c]", b, e);
}
private String nDigits(int n) {
return nDigits(n, n);
}
private String nDigits(int n, int m) {
return "[0-9]" + String.format(n==m ? n==1 ? "":"{%d}":"{%d,%d}", n, m);
}
private String eqLengths(String from, String to) {
char fc = from.charAt(0), tc = to.charAt(0);
if (from.length() == 1 && to.length() == 1)
return charClass(fc, tc);
if (fc == tc)
return fc + "("+rangeRegex(from.substring(1), to.substring(1))+")";
String re = fc + "(" + baseRange(from.substring(1), true, false) + ")|"
+ tc + "(" + baseRange(to.substring(1), false, false) + ")";
if (++fc <= --tc)
re += "|" + charClass(fc, tc) + nDigits(from.length() - 1);
return re;
}
private String nonEqLengths(String from, String to) {
String re = baseRange(from,true,false) + "|" + baseRange(to,false,true);
if (to.length() - from.length() > 1)
re += "|[1-9]" + nDigits(from.length(), to.length() - 2);
return re;
}
public String run(int n, int m) {
return "\\b0*?("+ rangeRegex("" + n, "" + m) +")\\b";
}
public String rangeRegex(String n, String m) {
return n.length() == m.length() ? eqLengths(n, m) : nonEqLengths(n, m);
}
}
答案 0 :(得分:0)
为此使用一个简单的界面
public interface Check {
boolean isValidFor(int value);
}
然后为不同类型的检查实现不同的类,例如
public class isEqualTo implements Check {
private int valueToTestAgainst;
public isEqualTo(int test) {
valueToTestAgainst = test;
}
public boolean isValidFor(int value) {
return valueToTestAgainst == value;
}
}
public class isGreatherThan implements Check {
private int valueToTestAgainst;
public isGreatherThan(int test) {
valueToTestAgainst = test;
}
public boolean isValidFor(int value) {
return valueToTestAgainst > value;
}
}
然后有一个类,它解析给定的输入并创建Check对象的列表。也许创建一个抽象类来保存检查值(valueToTestAgainst
)和/或使实现通用以支持其他类型,例如double。
答案 1 :(得分:-1)
根据条件,我尝试结合和减法的是'^(?! 250)0 *?([0-9] | 2(5([0-5])| [0-4] [0-9 ])| 1 [0-9] {2} | [1-9] [0-9] | 2000)$。在这种情况下,我们匹配1到255的范围和2000个数字(联合),并求和250(减去)。取反很好。