[英]How to Split a mathematical expression on operators as delimiters, while keeping them in the result?
[英]How to Split a logical expression on operators as delimiters, while keeping them in the result?
與這個問題類似,我想將我的邏輯表達式A >= 10 AND B <= 20 OR C in ('3', '4')
拆分為A
, >=
, 10
, AND
, B
, <=
, 20
, OR
, C
, in
, ('3', '4')
怎么做到呢?
我正在嘗試以下方式(但這似乎不是優雅的方法)
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);
你需要的正則表達式是這樣的:
\(.*\)|[^\s]+
您可以在 regex101.com 上找到帶有說明的示例。
在 Java 中,您必須匹配正則表達式並且不要對其進行拆分。 使用周圍的括號(\\(.*\\)|[^\\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.