ISAI student has asked for the wisdom of the Perl Monks concerning the following question:

Hello all. I am trying to get minimal matching to the end of the string. I will explain by an example. The code is:

perl -e '$a ="Inst1 cell1 ( .Q ( nets ) , .T (nety) ) ;\n"; $a=~s/\). +*?$//; print $a;'

The output is:

Inst1 cell1 ( .Q ( nets
I want it to be:
"Inst1 cell1 ( .Q ( nets ) , .T (nety) "

Now, I know of ways to do it, but not in 1 regexp

Replies are listed 'Best First'.
Re: minimal matching to end of string in regular expressions
by MVS (Monk) on Mar 04, 2012 at 06:26 UTC

    If you want to be sure that you're matching the last right parenthesis:

    $a =~ s/\)[^)]*$//;
Re: minimal matching to end of string in regular expressions
by jwkrahn (Abbot) on Mar 04, 2012 at 06:32 UTC
    $ perl -e '$a ="Inst1 cell1 ( .Q ( nets ) , .T (nety) ) ;\n"; $a=~s/( +.*\)).*/$1/; print $a;' Inst1 cell1 ( .Q ( nets ) , .T (nety) )
Re: minimal matching to end of string in regular expressions
by JavaFan (Canon) on Mar 04, 2012 at 11:43 UTC
    In general, if you want to find the last pattern in a string:
    /.*PAT/s;
    So, in your case:
    s/(.*)\).*/$1/s;
    You can also combine this with the \K construct:
    s/.*\K\).*//s
    BTW, your question makes it unclear to me whether you want to trailing newline to be removed. My code does, and your "want it to be" does not include a newline -- but your original solution does.
Re: minimal matching to end of string in regular expressions
by toolic (Bishop) on Mar 04, 2012 at 13:23 UTC
Re: minimal matching to end of string in regular expressions
by Anonymous Monk on Mar 04, 2012 at 18:20 UTC
    Better clear than clever.