正则表达式用括号提取单词之间的数据

时间:2014-01-29 20:43:37

标签: java regex

我在ANDOR运算符中有一些表达式。 +AND/OR。我需要在由运算符分隔的括号内提取表达式。

示例:

Expression                    Output

(A + B)/(C + D)              (A + B),   (C + D)
(A / B)+(C / D)              (A / B),   (C / D)
(A + B / C)+(A / B)          (A + B / C),   (A / B)

表达式可以有任何组合。我只需要看看逻辑运算符&在括号中获取数据。

exp.split("((?<=&&)|(?=&&)|(?<=\\|\\|)|(?=\\|\\|)|(?<=\\()|(?=\\()|(?<=\\))|(?=\\)))");

但这会分裂每个角色。我需要正则表达式来寻找运算符&amp;拆分,在上面的示例中引用的括号内的数据。

 If i also want the operator along with data how could it be done?

Example : 
(A + B)/(C + D)   should give me (A + B), /, (C + D)
(A + B / C)+(A / B) should give me (A + B / C), +, (A / B)

2 个答案:

答案 0 :(得分:1)

我认为你不能用split做到这一点。您可以使用正则表达式Matcher并迭代组:

String input = "(A + B / C)+(A / B)";

//capture a group for each expression contained by parentheses
Pattern pattern = Pattern.compile("(\\(.*?\\))");

//create a matcher to apply the pattern to your input
Matcher matcher = pattern.matcher(input);

//find every match and add them to a list
List<String> expressions = new ArrayList<>();
while(matcher.find()) {
    expressions.add(matcher.group());
}

System.out.println(expressions);

打印[(A + B / C), (A / B)]

答案 1 :(得分:0)

 If i also want the operator along with data how could it be done?

    Example : 
    (A + B)/(C + D)   should give me (A + B), /, (C + D)
    (A + B / C)+(A / B) should give me (A + B / C), +, (A / B)

要做到这一点,我希望这应该有效

exp.replaceAll("\\([^)]*?\\)", "")