ivowel wrote:

> 
> thank you, rob.  great reference.  now I know that it can be done.
> alas, this doc is a little over my head.  can someone who has used
> this construct possibly please show me how I would try it on my simple
> example?
> 
>   sample = " \caption{my table \label{table-label} example: $\sqrt{2+
> \sqrt{2}}$} more here {}"
> 
> 
> accomplishing this is actually not ugly at all in perl:
> 
>   use Regexp::Common;
>   my $matchingarg = qr/$RE{balanced}{-parens=>'{ }'})/;
>   /\\caption$matchingarg/;
>   print "The \\caption argument is $1\n";
> 
> of course, perl is ugly in many other respects, but here, it does
> nicely.
> 
> regards, /iaw


sample = " \\caption{my table \\label{table-label}
  example: $\\sqrt{2+\\sqrt{2}}$} more here {}"


def bal_fences str
  left = str[0,1]
  fences = /[#{Regexp.escape "(){}[]<>"[ /#{Regexp.escape left}./ ]}]/
  accum = "" ; count = 0
  str.scan( /.*?#{fences}/ ){|s|
    count += if s[-1,1] == left ; 1 else -1 end
    accum << s
    break if 0 == count
  }
  accum
end


p bal_fences( sample[ /caption(.*)/m, 1 ] )