如何在JavaScript中将输入括号与正则表达式匹配? [英] How to match a input parenthesis with regular expression in JavaScript?
本文介绍了如何在JavaScript中将输入括号与正则表达式匹配?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我不知道将输入括号与JavaScript匹配。
I have no idea on matching the input parenthesis with JavaScript.
输入字符串示例:
(pen)
((pen) and orange)
如果输入字符串如下所示,它应该返回false:
it should return false if the input string is like the following:
(pen
pen)
(pen) and orange)
((pen and orange )
((pen) and orange
)(pen and orange )(
(pen and )orange()
推荐答案
在没有任何组的情况下更换每一组left paren - some chars - right paren。如果结果字符串包含一个括号,则parens不平衡。
replace every group of "left paren - some chars - right paren" with nothing, until there is no more groups. If the resulting string contains a parenthesis, the parens were not balanced.
balancedParens = function(str) {
var q;
do {
q = str;
str = str.replace(/\([^()]*\)/g, '');
} while(q != str);
return !str.match(/[()]/);
}
a = "foo ((and) bar and (baz) quux) and (blah)";
b = "(dddddd()";
alert(balancedParens(a))
alert(balancedParens(b))
在javascript中无法将平衡字符串与单个正则表达式匹配,因为JS方言不支持递归表达式。
It's not possible to match a balanced string with a single regexp in javascript, because JS dialect doesn't support recursive expressions.
这篇关于如何在JavaScript中将输入括号与正则表达式匹配?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文