java - 多级字符串分割

标签 java

所以我的要求是这个的扩展: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

现在我可以找到OperandsRelational Operator使用上面链接中给出的答案。 但我怎样才能找到Conditional Operator并按上述格式打印?

最佳答案

您可以使用包含正则表达式的代码来根据您的需要解析值。

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

关于java - 多级字符串分割,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52928018/

相关文章:

java - 我在哪里放置 H2 触发器类?

java - PLS-00306 : wrong number or types of arguments in call to GET_NEW_EVENTS in Java

java - 使用 HttpServletResponseWrapper 捕获包括 header 在内的整个响应

java - 来自服务的通知

java - 接口(interface)层次结构: general purpouse and how to use it

java - 使用 Hibernate 将 csv 文件导入 MySQL 数据库

java - 无闪烁 AWT 应用程序

java - 从 ArrayList 中删除某些 TextView

java - 如何修复此 UnknownHostException?

java - 调用方法时不需要使用相同的参数名称吗?