【发布时间】:2018-12-24 10:04:54
【问题描述】:
在我的应用程序中,我需要数字的过滤器概念。所以我需要生成动态正则表达式格式。例如,如果我输入的是 (attrN = number,operator="equal",value=459) 和 (attrN = number,operator="小于等于",value=57) and (attrN = number,operator="not equal",value=45) and (attrN = number,operator="greaterthan equal",value=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);
}
}
【问题讨论】:
-
为什么需要正则表达式?在我看来,为此使用正则表达式会使解决方案变得非常复杂。这是“如果你只有一把锤子,一切看起来都像钉子”吗?
-
我需要开发一些人工智能来生成动态数字正则表达式。
-
除了来自@DawoodibnKareem 的非常中肯的评论,需要说的是没有问题被问到。
-
如果我给出小于 57 表示 0-57 范围。然后能够理解逻辑并发布有问题的逻辑。但是如何否定 0-57 之间的数字(^54)。在这个我不想要 54 值。