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 "(?<bal>" + "[^#{lclass}#{rclass}]*?" + "(?:\\#{lpar}\\g<bal>\\#{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/.