猿问

多级字符串拆分

我的输入字符串是这样的:


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并以上述格式打印呢?


qq_花开花谢_0
浏览 153回答 2
2回答

潇潇雨雨

您可以使用此包含正则表达式的代码根据您的需要解析值。public static void main(String[] args) {&nbsp; &nbsp; String str = "FEES_1 > 100 AND FEES_2 <= 200 OR FEES_3 <= 500";&nbsp; &nbsp; Pattern p = Pattern.compile("(?:^|(AND|OR))\\s*(\\w+)\\s+([<>]=?)\\s+(\\d+)\\s*(?=(AND|OR|$))");&nbsp; &nbsp; Matcher m = p.matcher(str);&nbsp; &nbsp; for (int i = 0; m.find(); i++) {&nbsp; &nbsp; &nbsp; &nbsp; System.out.println("Iteration " + (i + 1) + ":");&nbsp; &nbsp; &nbsp; &nbsp; System.out.println(String.format("Operands: [%s ,&nbsp; %s ]", m.group(2), m.group(4)));&nbsp; &nbsp; &nbsp; &nbsp; System.out.println("Relational Operator: " + m.group(3));&nbsp; &nbsp; &nbsp; &nbsp; System.out.println("Conditional Operator: " + m.group(1));&nbsp; &nbsp; &nbsp; &nbsp; System.out.println();&nbsp; &nbsp; }}此代码提供了与您想要的完全匹配的以下输出。Iteration 1:Operands: [FEES_1 ,&nbsp; 100 ]Relational Operator: >Conditional Operator: nullIteration 2:Operands: [FEES_2 ,&nbsp; 200 ]Relational Operator: <=Conditional Operator: ANDIteration 3:Operands: [FEES_3 ,&nbsp; 500 ]Relational Operator: <=Conditional Operator: OR

噜噜哒

如果你 100% 确定输入字符串是这种格式,那么你可以简单地做这样的事情。它更简单和直接,不需要任何正则表达式。String[] parts = string.split(" ");按空格分割输入字符串,然后对于每个连续的迭代,您可以像这样打印int end = (parts.length + 1)/4;for(int i =0;i<end;i++){&nbsp; &nbsp; System.out.println("Iteration : " + (i+1));&nbsp; &nbsp; System.out.println("Operands: [ " + parts[4*i] + " , " + parts[4*i + 2] + "]");&nbsp; &nbsp; System.out.println("Relational Operator: " + parts[4*i + 1]);&nbsp; &nbsp; System.out.println("Conditional Operator: " + ((i>0)?parts[4*i - 1]:null));}
随时随地看视频慕课网APP

相关分类

Java
我要回答