[英]How to match a input parenthesis with regular expression in JavaScript?
I have no idea on matching the input parenthesis with JavaScript. 我不知道将输入括号与JavaScript匹配。
Input string example: 输入字符串示例:
(pen)
((pen) and orange)
it should return false if the input string is like the following: 如果输入字符串如下所示,则应返回false:
(pen
pen)
(pen) and orange)
((pen and orange )
((pen) and orange
)(pen and orange )(
(pen and )orange()
Regular expressions would be messy. 正则表达式会很杂乱。 It's much easier to go through with a simple counter. 一个简单的计数器要容易得多。
function parenthesesBalanced(string) {
var count = 0;
for (var i = 0, l = string.length; i < l; i++) {
var char = string.charAt(i);
if (char == "(") {
// Opening parenthesis is always OK
count++;
} else if (char == ")") {
// If we're at the outer level already it's not valid
if (count == 0) return false;
count--;
}
}
return (count == 0);
}
It is a known hard problem to match parens with regular expressions. 这是一个已知的难题 ,以配合正则表达式的括号。 While it is possible, it's not particularly efficient. 尽管有可能,但它并不是特别有效。
It's much faster simply to iterate through the string, maintaining a counter, incrementing it every time you hit an open paren, and decrementing it every time you hit a close paren. 简单地遍历字符串,维护一个计数器,每次击中一个打开的paren时将其递增,并在每次击中一个紧密的paren时将其递减则要快得多。 If the counter ever goes below zero, or the counter is not zero at the end of the string, it fails. 如果计数器曾经低于零,或者在字符串末尾计数器不为零,则它将失败。
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))
http://jsfiddle.net/gvGGT/ http://jsfiddle.net/gvGGT/
It's not possible to match a balanced string with a single regexp in javascript, because JS dialect doesn't support recursive expressions. 在javascript中,不可能用单个正则表达式来匹配平衡字符串,因为JS方言不支持递归表达式。
I made a node library call balanced to make this a bit more sane, if you wanted to just get balanced outer matches you can do this 我进行了一个平衡的节点库调用,以使其更加理智,如果您只想获得平衡的外部匹配,则可以这样做
balanced.matches({source: source, open: '(', close: ')'})
my use case was a bit more complicated, and required me to do replacements and support comments. 我的用例有点复杂,需要我做替换和支持意见。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.