所以我的要求是对此的扩展:Obtaining the split value after java string split
我的输入字符串是这样的:
FEES_1 > 100 AND FEES_2 <= 200 OR FEES_3 <= 500
我需要遍历各个条件,我想知道哪个条件运算符分隔每个条件。
预期输出:-
Iteration 1:
Operands: [FEES_1 , 100 ]
Relational Operator: >
Conditional Operator: null
Iteration 2:
Operands: [FEES_2 , 200 ]
Relational Operator: <=
Conditional Operator: AND
Operands: [FEES_3 , 500 ]
Relational Operator: <=
Conditional Operator: OR
现在我可以使用上面链接中给出的答案找到Operands
和Relational Operator
。
但是如何找到Conditional Operator
并以上述格式打印呢?
答案 0 :(得分:1)
您可以使用此包含正则表达式的代码来根据需要解析值。
public static void main(String[] args) {
String str = "FEES_1 > 100 AND FEES_2 <= 200 OR FEES_3 <= 500";
Pattern p = Pattern.compile("(?:^|(AND|OR))\\s*(\\w+)\\s+([<>]=?)\\s+(\\d+)\\s*(?=(AND|OR|$))");
Matcher m = p.matcher(str);
for (int i = 0; m.find(); i++) {
System.out.println("Iteration " + (i + 1) + ":");
System.out.println(String.format("Operands: [%s , %s ]", m.group(2), m.group(4)));
System.out.println("Relational Operator: " + m.group(3));
System.out.println("Conditional Operator: " + m.group(1));
System.out.println();
}
}
此代码完全按照您的要求提供以下输出匹配。
Iteration 1:
Operands: [FEES_1 , 100 ]
Relational Operator: >
Conditional Operator: null
Iteration 2:
Operands: [FEES_2 , 200 ]
Relational Operator: <=
Conditional Operator: AND
Iteration 3:
Operands: [FEES_3 , 500 ]
Relational Operator: <=
Conditional Operator: OR
答案 1 :(得分:0)
@Warren如果您100%确定输入字符串具有这种格式,则可以简单地执行以下操作。它更简单直接,不需要任何正则表达式。
String[] parts = string.split(" ");
用空格将输入字符串分开,然后对于每次连续的迭代,您都可以这样打印
int end = (parts.length + 1)/4;
for(int i =0;i<end;i++){
System.out.println("Iteration : " + (i+1));
System.out.println("Operands: [ " + parts[4*i] + " , " + parts[4*i + 2] + "]");
System.out.println("Relational Operator: " + parts[4*i + 1]);
System.out.println("Conditional Operator: " + ((i>0)?parts[4*i - 1]:null));
}