Given the following input:
$ cat liltester
if ((ret = utMemAlloc(
pManeuverObj->util.hMemory,
1,
(usTxtLen + 1),
(void **)&pMnvr->Context.pDestinationString
)) < 0)
The following produces the expected output (it strips out everything outside the outer parens)
$ perl -0 -ne 'print $1 if /((?:\((?>[^()]|(?R))*\)))/g' liltester
I grabbed that from https://www.regular-expressions.info/recurse.html , by the way. However, it's been modified to 1) capture, and have the "balanced" portion be inside a non-capturing group. The idea being I can do this
$ perl -0 -ne 'print $1 if /(utMemAlloc(?:\((?>[^()]|(?R))*\)))/g' liltester
without modifying (
being considered as my opening paren. (As obviously trying to match utMemAlloc(
with )
is not going to work well.)
However, the output is a blank line. Expected output is:
utMemAlloc(
pManeuverObj->util.hMemory,
1,
(usTxtLen + 1),
(void **)&pMnvr->Context.pDestinationString
)
My end goal, for what it's worth, is to find instances of utMemAlloc
that use pDestinationString
in the parameter list.
The following produces the expected output, by the way, but I'd prefer to avoid it for several reasons (one of which is that $RE{balanced}
seems to blow up perl for an entire shell instance whenever I use it wrong):
perl -MRegexp::Common -0 -ne 'print $1 if /(utMemAlloc$RE{balanced}{-parens=>'"'"'()'"'"'})/g' liltester
Optional Reading
The other reason I prefer to avoid Regexp::Common
is that I often use perl in a mingw terminal provided by a git UI..Basically to avoid having to push code through git to a linux box. The actual code I ended up with (thanks to the current answer) is:
$ git grep -l 'pDestinationString' |
xargs perl -0 -lne 'print for /(utMemAlloc\s*(\((?>[^()]|(?-1))*\)))/g' |
perl -0 -ne 'print "$_\n\n\n" if /utMemAlloc[\s\S]*pDestinationString/'
The 2nd test for utMemAlloc was necessary because there are two capture groups in the first expression, and when I tried to make the inner one a non-capturing group, the whole expression stopped working again. This works, but it's damn ugly.