Home > Software design >  How to split a string in java which has comparison operators
How to split a string in java which has comparison operators

Time:10-02

I am using string in the below format where i need to iterate the strings seperated by ",":

<field_path1><operator1><value1/regex1>,<field_path2><operator2><value2/regex2>

ex: fare.details.type!="AB", id.name.first=="QWERT"

fare.details.type is a field defined in a protobuf file.

First i split the string using "," to get different conditions and then I tried to split the string using delimeter as the operators "==", "!=" and "~=".

String[] operator = string.split("==|\\!=|\~=");

In the end i need to do a comparison of the string in the below format. Using the split operator i don't get the exact operator which is used exactly in the string.

if (fare.details.type!="AB")

Please help if anyone knows how to approach it or if can split it it some other way.

CodePudding user response:

Are you trying to extract the operator and the operands from each expression? Maybe you should try de regex Pattern API.

    Pattern p = Pattern.compile("^(. )(==|\\!=|\\~=)(. )");
    String string = "fare.details.type!=\"AB\";
    Matcher m = p.matcher(string);
    if (m.find()) {
        String fieldPath = m.group(1);
        String operator = m.group(2);
        String value = m.group(3);
    }
  • Related