Reputation: 1893
I have no idea on matching the input parenthesis with JavaScript.
Input string example:
(pen)
((pen) and orange)
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()
Upvotes: 0
Views: 1613
Reputation: 9859
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.
Upvotes: 0
Reputation: 90752
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);
}
Upvotes: 3
Reputation: 53940
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))
It's not possible to match a balanced string with a single regexp in javascript, because JS dialect doesn't support recursive expressions.
Upvotes: 1
Reputation: 8417
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. If the counter ever goes below zero, or the counter is not zero at the end of the string, it fails.
Upvotes: 1