From: "Wolfgang Nádasi-Donner" Date: 2007-10-09T16:30:32+09:00 Subject: Re: regexp question - look for parentheses then remove them Jesús Gabriel y Galán wrote: > I've read that the .NET regex engine has some constructs to recognize > balanced constructs like parens... It's possible in Ruby 1.9 or Ruby 1.8 and the Oniguruma library too: module Matchelements def bal(lpar='(', rpar=')') raise RegexpError, "wrong length of left bracket '#{lpar}' in bal" unless lpar.length == 1 raise RegexpError, "wrong length of right bracket '#{rpar}' in bal" unless rpar.length == 1 raise RegexpError, "identical left and right bracket '#{lpar}' in bal" if lpar.eql?(rpar) lclass, rclass = lpar, rpar lclass = '\\' + lclass if lclass.match(/[\-\[\]]/) rclass = '\\' + rclass if rclass.match(/[\-\[\]]/) return "(?" + "[^#{lclass}#{rclass}]*?" + "(?:\\#{lpar}\\g\\#{rpar}" + "[^#{lclass}#{rclass}]*?" + ")*?" + ")" end end include Matchelements result = "3 * (2 + (1 + 3)) + (1 * 4)".scan(/\(#{bal()}\)/) p result # => [["2 + (1 + 3)"], ["1 * 4"]] Wolfgang Nádasi-Donner -- Posted via http://www.ruby-forum.com/.