[英]How to Split a logical expression on operators as delimiters, while keeping them in the result?
Similar to this question I want to split my logical expression A >= 10 AND B <= 20 OR C in ('3', '4')
to A
, >=
, 10
, AND
, B
, <=
, 20
, OR
, C
, in
, ('3', '4')
与这个问题类似,我想将我的逻辑表达式
A >= 10 AND B <= 20 OR C in ('3', '4')
拆分为A
, >=
, 10
, AND
, B
, <=
, 20
, OR
, C
, in
, ('3', '4')
how can it be done?怎么做到呢?
I am trying following way(but this doesnt seems to be elegant approach)我正在尝试以下方式(但这似乎不是优雅的方法)
String orRules[] = inputRule.split(" OR ");
for (int i = 0; i < orRules.length; i++) {
String andRules[] = orRules[i].split(" AND ");
for (int j = 0; j < andRules.length; j++) {
String[] result = andRules[j].split("(?<=[-+*/])|(?=[-+*/])");
System.out.println(Arrays.toString(result));
}
orRules[i] = String.join(" AND ", andRules);
}
output = String.join(" OR ", orRules);
The regex you need is something like this:你需要的正则表达式是这样的:
\(.*\)|[^\s]+
You can find an example here on regex101.com with explanation.您可以在 regex101.com 上找到带有说明的示例。
In Java you have to to match the regex and don't split on it.在 Java 中,您必须匹配正则表达式并且不要对其进行拆分。 With the surrounding brackets
(\\(.*\\)|[^\\s]+)+
you are creating groups, which can be found like in the following example:使用周围的括号
(\\(.*\\)|[^\\s]+)+
您正在创建组,可以在以下示例中找到它:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
...
public static void main(String[] args) {
String ex = "A >= 10 AND B <= 20 OR C in ('3', '4')";
String regex ="(\\(.*\\)|[^\\s]+)+";
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(ex);
while(m.find()) {
System.out.println(m.group(1));
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.