简体   繁体   English

多级字符串拆分

[英]Multi-level String split

So My requirement is an extension of this: Obtaining the split value after java string split所以我的要求是这个的扩展: 在java字符串拆分后获取拆分值

My input string is something like this:我的输入字符串是这样的:

FEES_1 > 100 AND FEES_2 <= 200 OR FEES_3 <= 500

I need to iterate over individual conditions and I would like to know which is the conditional operator seperating each conditions.我需要迭代单个条件,我想知道哪个是分隔每个条件的条件运算符。

Expected Output:-预期输出:-

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

Now I can find Operands and Relational Operator using the answer given in above link.现在我可以使用上面链接中给出的答案找到OperandsRelational Operator But how can I find the Conditional Operator and print it in above format?但是我怎样才能找到Conditional Operator并以上述格式打印呢?

You can use this code which contains regex to parse the values as per your needs.您可以使用此包含正则表达式的代码根据您的需要解析值。

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();
    }
}

This code gives following output matching exactly as you wanted.此代码提供了与您想要的完全匹配的以下输出。

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

@Warren if you are 100% sure that input string is of this format, then you can simply do something like this. @Warren 如果你 100% 确定输入字符串是这种格式,那么你可以简单地做这样的事情。 It is much simpler and straight forward, no need of any regex.它更简单和直接,不需要任何正则表达式。

String[] parts = string.split(" ");

split the input string by spaces and then for each successive iteration you can print like this按空格分割输入字符串,然后对于每个连续的迭代,您可以像这样打印

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));
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM