Check if parenthesis has been closed

I need a Regex that checks if inside the String, the parenthesis has been closed.

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 done as Regex, but if it is difficult or impossible, it can be otherwise, but my irreducible requirement is that it be in pure JavaScript.

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

Author: brasofilo, 2014-08-10

2 answers

You are looking for a parentheses balancing algorithm.

Algorithm definition: scroll through the string character by character recording the amount of open parentheses and the amount 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 .

 8
Author: Anthony Accioly, 2020-06-11 14:45:34

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

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

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

 6
Author: mgibsonbr, 2017-04-13 12:59:39