Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things
 
PerlMonks  

Re: Regex problem - (non)greedy?

by hdb (Monsignor)
on Nov 14, 2013 at 14:29 UTC ( [id://1062592]=note: print w/replies, xml ) Need Help??


in reply to Regex problem - (non)greedy?

The non-greedy regex would still start at the first occurence of 'cd' but then stop at the first 'ghi', whereas the greedy one would stop at the last 'ghi'. (In your example there is only one, so they are the same.)

You can use this behavior to achieve the desired effect by adding something greedy before the expression of interest, like

$x =~ /.*cd (.*) ghi/;

Here the .* at the beginning would eat up everything up the last occurrence of 'cd', which is what you want.

Replies are listed 'Best First'.
Re^2: Regex problem - (non)greedy?
by ikegami (Patriarch) on Nov 14, 2013 at 14:31 UTC

    I expect that doesn't give the intended results for any of the following:

    "cdghi" "cd ghi ghi"

    Furthermore, that pattern won't help if we wants to go on to handle either of the following:

    "cd XXX ghi cd YYY ghi" "cd XXX cd YYY ghi ZZZ ghi"

    By the way, you really want to add a leading ^ to that to speed things up greatly when the pattern doesn't match.

      I am not sure what the expected results are, but the actual results are:

      cdghi: (no match) cd ghi ghi: ghi cd abc ghi cd def ghi: def
        I expect he'd want "" for the first and "" for the second. As for the third, see my update.
Re^2: Regex problem - (non)greedy?
by LanX (Saint) on Nov 14, 2013 at 14:37 UTC
    I think
    $x =~ /.* cd (.*?) ghi/x

    Is better, but can't test ATM... : )

    Cheers Rolf

    ( addicted to the Perl Programming Language)

    update

    Moved ? into group...

    PS: ikegami msged me in the meantime thx :)

    update

     > ikegami says Re Re^2: Regex problem - (non)greedy? By the way, you really want to add a leading ^ to that to speed things up greatly when the pattern doesn't match.

    He's (normally) right! ++

    might depend on how nifty Perl optimized the regex...

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1062592]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others wandering the Monastery: (2)
As of 2024-04-20 03:18 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found