Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much
 
PerlMonks  

Re: Substitute _last_ occurence in string?

by Wookie (Beadle)
on Jul 25, 2001 at 18:46 UTC ( [id://99696]=note: print w/replies, xml ) Need Help??


in reply to Substitute _last_ occurence in string?

You can try to use the fact that '*' is greedy:
$string=~s/(.*) two(.*)/$1$2/g;
When the first '.*' matches - it should go to the end of the line - and then work right to left to match the next part of the regex.

So in this case - it should find the last one.
game(Wookie,opponent) eq 'Wookie' ? undef $problem : remove_limbs(arms,opponent);

Replies are listed 'Best First'.
Re: Re: Substitute _last_ occurence in string?
by Hofmator (Curate) on Jul 25, 2001 at 19:05 UTC

    This can be expressed a little bit simpler: $string=~s/(.*) two/$1/; The /g modifier is not necessary - there will be only one match. And you don't want to change anything after the match so you don't have to capture and replace it.

    -- Hofmator

      This assumes that there is more than one 'two'. If there's only one instance, then the first instance is the last instance. I'd change this to:

      $string =~ s/(.*)\s*two/$1/; That way, you'll catch it if it's the first characters in the string.

      Update: Ok. Given the suggestions, How about:

      $string =~ s/(.*)(^|\s+)two/$1/;

        This assumes that there is more than one 'two'
        No, it doesn't. The only problem comes from the handling of surrounding spaces, but that goes for most solutions here. Your solution eats up all whitespace before the 'two' - and kills words like 'onetwo'. These things might or might not be OK, depending on what you want to do with the string afterwards ... but we don't know.

        So there is mtowtdi - surprise :) - but without more information, we can't tell which works best.

        -- Hofmator

        But that would match and replace the two in "twenty-two" as well, and probably this is not the desired behaviour.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others having an uproarious good time at the Monastery: (4)
As of 2025-03-18 05:07 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    When you first encountered Perl, which feature amazed you the most?










    Results (56 votes). Check out past polls.