简体   繁体   中英

How to split a string in java by logical operators (and, or) but not consider them if they appear in quotes?

I have a string that I need to split by logical operators "and", "or" (case insensitive). However, I should not be considering these logical operator patterns if they appear in quotes, single or double. A sample pattern:

contains(field1,'sample') or contains(field2,'aaandbb') AND (field3 gt 5000)

The output of the split I am trying to achieve:

contains(field1,'sample')

contains(field2,'aaandbb')

(field3 gt 5000)}

Note: Please ignore the brackets.

My code:

String soregex1="\\s+(?i)(and)|(or)\\s+";
    String[] splitStr = so1.split(soregex1);
    for(String str1:splitStr) {
        System.out.println(str1);
    }

All good except when pattern, that is, conditional operators, start appearing as values to string conditions. For example:

contains(field1,'sam or ple') or contains(field2,'aa and bb') AND (field3 gt 5000)

The output for above string with my code is:

contains(field1,'sam

ple')

contains(field2,'aa

bb')

(field3 gt 5000)

instead of

contains(field1,'sam or ple')

contains(field2,'aa and bb')

(field3 gt 5000)

I also need to factor in escaped singleor double quotes. Appreciate any suggestions on how to avoid considering pattern matches that appear in single quotes or double quotes.

have you tried this:

(\\)\\s*(AND))|(\\)\\s*(OR))

demo

This is a bit wild and crazy, but why not match the tokens themselves instead of splitting on the delimiter. (I'm assuming the (...) is mandatory. Case insensitive match)

\\w*\\(.*?\\)(?=\\s*(?:and|or|$))

( demo )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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