java 正则表达式检查括号是否平衡

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3918681/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 03:57:54  来源:igfitidea点击:

Regexp to check if parentheses are balanced

javaregex

提问by grapescan

Possible Duplicate:
Can regular expressions be used to match nested patterns?

可能的重复:
可以使用正则表达式来匹配嵌套模式吗?

I am writing a regexp to check if the input string is a correct arithmetic expression. The problem is checking if there are enough opening and closing parentheses.

我正在编写一个正则表达式来检查输入字符串是否是正确的算术表达式。问题是检查是否有足够的左括号和右括号。

Expressions:

表达式:

  1. (1)

  2. (((1)

  3. ((1))))

  1. (1)

  2. (((1)

  3. ((1))))

I think lookahead and lookbehind are useful here but for now I could check only one kind. I'm using Java, if it matters.

我认为前瞻和后视在这里很有用,但现在我只能检查一种。如果重要的话,我正在使用 Java。

回答by Mark Byers

You shouldn't use regular expression to do this. Instead you can iterate over the string character by character and keep track of the nesting level.

您不应该使用正则表达式来执行此操作。相反,您可以逐个字符地遍历字符串并跟踪嵌套级别。

Initially the nesting is 0. When you see a (increase the nesting by 1, and when you see )decrease the nesting. The expression is correctly balanced if the final nesting is 0 and the nesting never goes below 0.

最初的嵌套是 0。当你看到(增加 1 的嵌套,当你看到)减少嵌套。如果最终嵌套为 0 并且嵌套永远不会低于 0,则表达式是正确平衡的。

public static boolean checkParentheses(String s) {
    int nesting = 0;
    for (int i = 0; i < s.length(); ++i)
    {
        char c = s.charAt(i);
        switch (c) {
            case '(':
                nesting++;
                break;
            case ')':
                nesting--;
                if (nesting < 0) {
                    return false;
                }
                break;
        }
    }
    return nesting == 0;
}

回答by Hank Gay

You need to be using a parser to do this, not a regex. See this question.

您需要使用解析器来执行此操作,而不是正则表达式。看到这个问题

回答by Wayne Werner

Why not just count the opening and closing parens like so?

为什么不像这样计算开头和结尾的括号?

String expression = "((1+x) - 3 * 4(6*9(12+1)(4+(2*3+(4-4)))))";

int open = 0;
for(int x = 0; x < open; x++){
   if(expression[x] == '(')
      open++;
   else if(expression[x] == ')')
      open--;
}
if (open != 0)
   // Not a valid expression

Of course this only checks that you have the right amount - someone could write '))3*4((' and it would be validated using this method.

当然,这只检查您是否拥有正确的数量 - 有人可以写 '))3*4((' 并且它将使用此方法进行验证。