Beefy Boxes and Bandwidth Generously Provided by pair Networks Frank
No such thing as a small change
 
PerlMonks  

minimal matching to end of string in regular expressions

by ISAI student (Scribe)
on Mar 04, 2012 at 06:16 UTC ( #957732=perlquestion: print w/ replies, xml ) Need Help??
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

Comment on minimal matching to end of string in regular expressions
Select or Download Code
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 (Monsignor) 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 (Chancellor) 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.

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://957732]
Approved by Old_Gray_Bear
Front-paged by Corion
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others exploiting the Monastery: (6)
As of 2014-04-19 14:11 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    April first is:







    Results (481 votes), past polls