Please tell me the regular expression to check for the same number of open and closed brackets in the string.

  • 3
    Why regular? What is a simple calculation does not suit? - gil9red
  • one
    This is not such an easy task, since a balanced bracket expression is not described by regular grammar. However, regulars are already able to irregular grammars. - VladD 4:34 pm
  • one
    @VladD, and if as it is written - just for the same amount, without balance? - Qwertiy
  • 2
    @Alex: ()))(( - VladD
  • one
    I fall asleep. Not sure if everything is right: regex101.com/r/uP1dX9/2 test , who is interested in the question, please. - ReinRaus

1 answer 1

I strongly do not recommend
solve similar problems using regular expressions, if only out of theoretical curiosity, then to calculate that the text has the same number of opening and closing brackets using regular expressions, you need to have support for recursive patterns in the regular expression engine.

The first regular expression assumes that the text consists solely of brackets:

 (^((?:<(?2)>|>(?2)<|)++)$) 

https://regex101.com/r/uP1dX9/2

The second regular expression allows any other characters in the text:

 (^([^<>]*+(?:<(?2)>|>(?2)<|)++)[^<>]*$) 

https://regex101.com/r/uP1dX9/3

I recommend to pay attention to the value of Steps. Regular expressions for practical use in this case - the worst idea.