Check if parentheses have been closed

7

I need a Regex that checks whether the parentheses have been closed within the string .

This is my example:

/regex/.test("fdfdfdf(ddsd");  //retorna false, porque o parentese nao foi fechado;.

/regex/.test("fdfedff(ffd)dd") //retorma true,  porque o parentese foi fechado;.

My preference is that it be made as Regex, but if it is difficult or impossible, it may be otherwise, but my irreducible requirement is that it be in pure JavaScript.

Note: This will be done in a text box, so the number of characters inside and outside the parenthesis will vary.

    
asked by anonymous 10.08.2014 / 21:36

2 answers

8

You look for a parent-balance algorithm.

Algorithm definition: Traverse the String character to character by recording the number of open parentheses and the number of closed parentheses. If, at any time quantidade de parenteses abertos - quantidade de parenteses fechados < 0 then this is an invalid expression. If at the end of the String this balance is positive then there are open parentheses.

function isBalanced(s)
{
  var open = (arguments.length > 1) ? arguments[1] : '(';
  var close = (arguments.length > 2) ? arguments[2] : ')';  
  var c = 0;
  for(var i = 0; i < s.length; i++)
  {
    var ch = s.charAt(i);
    if ( ch == open )
    {
      c++;
    }
    else if ( ch == close )
    {
      c--;
      if ( c < 0 ) return false;
    }
  }
  return c == 0;
}

Source: RossetaCode.org - Balanced brackets

UPDATE

Functional example in Ideone .

    
10.08.2014 / 22:23
6

If you have a fixed number of parentheses (eg 1 and only 1 - not zero or one, not one or two, only one) you can do with the following regex:

[^()]*[(][^()]*[)][^()]*

Otherwise it is impossible to do with regex (does not match a regular language ). See Anthony Accioly's answer for a possible solution.

    
10.08.2014 / 23:20