繁体   English   中英

Java-正则表达式为运算符拆分数学表达式,但不包括括号中的运算符

[英]Java - Regex to split mathematical expression for operator excluding operator which comes under brackets

我需要使用正则表达式下面的字符串。 但它会分割括号内的数据。

Input
T(i-1).XX_1 + XY_8 + T(i-1).YY_2 * ZY_14

Expected Output
T(i-1).XX_1 , XY_8 , T(i-1).YY_2 , ZY_14

它不应拆分“(”和“)”下的数据;

我尝试使用下面的代码,但拆分了“(”和“)”下的数据

String[] result = expr.split("[+*/]");

任何解决此问题的指针。

我是这个正则表达式的新手。

Input
(T(i-1).XX_1 + XY_8) + T(i-1).YY_2 * (ZY_14 + ZY_14)
Output
T(i-1).XX_1 , XY_8 , T(i-1).YY_2 , ZY_14 , ZY_14

如果是T(i-1),则需要忽略。

对于下面的表达式,它不起作用

XY_98 + XY_99 +XY_100
String lineExprVal = lineExpr.replaceAll("\\s+","");
String[] result = lineExprVal.split("[+*/-] (?!(^))");

您可以像这样在括号内分割所有内容:

String str = "T(i-1).XX_1 + XY_8 + T(i-1).YY_2 * ZY_14";
String result[] = str.split("[+*/-] (?!(^))");
//---------------------------^----^^--List of your delimiters

System.out.println(Arrays.toString(result));

这将打印:

[T(i-1).XX_1 , XY_8 , T(i-1).YY_2 , ZY_14]

这个想法很简单,您必须使用不在括号内的定界符进行拆分。

您可以在此处检查ideone ,也可以在此处检查您的regex regex 演示


编辑

在第二种情况下,您必须使用此正则表达式:

String str = "(T(i - 1).XX_1 + XY_8)+  (i - 1).YY_2*(ZY_14 + ZY_14)";
String result[] = str.split("[+*+\\/-](?![^()]*(?:\\([^()]*\\))?\\))");

System.out.println(Arrays.toString(result));

这将给您:

[(T(i-1).XX_1+XY_8), T(i-1).YY_2, (ZY_14+ZY_14)]
 ^----Group1------^  ^--Groupe2-^  ^--Groupe3-^

您可以找到Regex演示 ,我在此通过Regex启发了此解决方案,该表达式仅匹配逗号,而不匹配多个括号

希望这可以帮到你。

如果不可能的话,很难拆分第二个数学表达式,因此您必须使用pattern ,它更有用,因此对于您的表达式,您需要以下正则表达式:

(\w+\([\w-*+\/]+\).\w+)|((?:(\w+\(.*?\))))|(\w+)

这是一个演示正则表达式,您将了解更多。

为了得到结果,您需要循环抛出结果:

public static void main(String[] args) {

    String input = "(T(i-1).XX_1 + XY_8) + X + T(i-1).YY_2 * (ZY_14 + ZY_14) + T(i-1)";

    Pattern pattern = Pattern.compile("(\\w+\\([\\w-*+\\/]+\\).\\w+)|((?:(\\w+\\(.*?\\))))|(\\w+)");
    Matcher matcher = pattern.matcher(input);

    List<String> reslt = new ArrayList<>();
    while (matcher.find()) {//loop throw your matcher 
        if (matcher.group(1) != null) {
            reslt.add(matcher.group(1));
        }
//In your case you have to avoid this two groups 
//            if (matcher.group(2) != null) {
//                reslt.add(matcher.group(2));
//            }
//            if (matcher.group(3) != null) {
//                reslt.add(matcher.group(3));
//            }
        if (matcher.group(4) != null) {
            reslt.add(matcher.group(4));
        }
    }
    reslt.forEach(System.out::println);
}

这将为您提供:

T(i-1).XX_1
XY_8
X
T(i-1).YY_2
ZY_14
ZY_14

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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