As phils already pointed out in his comment forward-sexp
is the function that parses balanced expressions.
You could modify your example as follows to match the balanced expression with vanilla emacs:
#!/usr/bin/env emacs --script
(setq str "foo(bar(),hee()) out()")
(with-temp-buffer
(insert str)
(goto-char (point-min))
(let (end)
(when (and (search-forward "foo(" nil t)
(condition-case err
(setq end (scan-sexps (1- (point)) 1))
(scan-error nil)))
(print (buffer-substring (match-beginning 0) end))
)))
I already pointed out in my comment that I would use cexp.
In that case the modified code would be:
#!/usr/bin/env emacs --script
(setq str "foo(bar(),hee()) out()")
(require 'cexp)
(with-temp-buffer
(insert str)
(goto-char (point-min))
(when (cexp-search-forward "foo\\!(\\`(\\!)" nil t)
(print (match-string 0))))
The parts of the combined expression "foo\\!(\\`(\\!)"
:
foo
matches itself
\!(...\!)
matches a balanced expression
\`...
at the very beginning of the balanced expression...
(
should be a parenthesis
syntax-ppss
if you want to find balanced parens. – Jordon Biondo Oct 15 '18 at 20:54forward-sexp
to move over a balanced expression. – phils Oct 15 '18 at 21:01