Regexp检查括号是否平衡 [英] Regexp to check if parentheses are balanced

查看:77
本文介绍了Regexp检查括号是否平衡的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

正则表达式可用于匹配嵌套模式吗?

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

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.

表达式:


  1. (1)

  1. (1)

(((1)

( (1))))

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

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

推荐答案

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

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.

最初嵌套为0.当您看到将嵌套增加1,当看到减少嵌套。如果最终嵌套为0且嵌套永远不会低于0,则表达式会正确平衡。

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.

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;
}

这篇关于Regexp检查括号是否平衡的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆