Check if parenthesis has been closed

Asked

Viewed 917 times

7

I need a Regex to check 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 was done 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.

  • I didn’t understand your doubt.

  • @Jorge B. I need one regex check that inside the string, the parenthesis has been closed.

  • @Anthonyaccioly, could you make a demonstration of how this would be done?

  • @Samirbraga, feito.

2 answers

8


You are looking for a parenthesis balancing algorithm.

Algorithm Definition: Go through the String character by character recording the amount 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.

  • Could you put your example on jsFiddle, because I’m having a hard time.

  • After stopping for a while, I got the result I wanted, with your code.

  • Quiet. I left an example of Ideone, it seems that jsfiddle is offline.

  • 2

    parece que o jsfiddle está offline, jej, and half of the publications in [so] were for cucuias!

6

If you have a number fixed in brackets (e.g..: 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 (it does not correspond to a regular language). Behold the answer from Anthony Accioly for a possible solution.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.