gpt4 book ai didi

java - java中数字的正则表达式

转载 作者:太空宇宙 更新时间:2023-11-04 09:57:41 25 4
gpt4 key购买 nike

在我的应用程序中,我需要数字的过滤器概念。因此,我需要生成动态正则表达式格式。例如,如果我给出的输入类似于 (attrN = number,operator="equal",value=459) 和 (attrN = number,operator="lessthan equal",value=57) 和 (attrN = number,operator="not equal",value=45) 和 (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);
}
}

最佳答案

为此使用一个简单的界面

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。

关于java - java中数字的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53911929/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com