问题描述
我正在编写一个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))))
我认为前瞻和后瞻在这里很有用但是现在我只能检查一种。我正在使用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检查括号是否平衡的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!