Beefy Boxes and Bandwidth Generously Provided by pair Networks
Don't ask to ask, just ask

Match last instance of pattern

by techie411 (Acolyte)
on Nov 05, 2008 at 21:41 UTC ( #721825=perlquestion: print w/replies, xml ) Need Help??
techie411 has asked for the wisdom of the Perl Monks concerning the following question:

I'm trying to do a Perl one-liner to replace ONLY the last </TABLE> Tag and replace it with something. I tried the following, but it doesn't work:

 perl -pi -e 's/.*<\/TABLE>/REPLACE/' test.htm

The following doesn't just match the last one but also replaces another </TABLE> tag. Any assistance appreciated. Thanks.

Replies are listed 'Best First'.
Re: Match last instance of pattern
by JStrom (Pilgrim) on Nov 05, 2008 at 22:22 UTC
    No need to involve the regex engine.

    perl -0777 -pe "substr $_, rindex($_,'</TABLE>'), 8, 'REPLACE'" x.html

Re: Match last instance of pattern
by moritz (Cardinal) on Nov 05, 2008 at 21:59 UTC
    If you run perl 5.10.0 or later, you can use this regex: s/.*\K<\/TABLE>/REPLACE/

    If you're not that fortunate, you could use captures: s/(.*)<\/TABLE>/${1}REPLACE/

Re: Match last instance of pattern
by GrandFather (Sage) on Nov 05, 2008 at 22:41 UTC

    Is there only one line in the file you are processing? If not you have something of a problem because the substitution is applied to each line in the file.

    Perl reduces RSI - it saves typing
Re: Match last instance of pattern
by ccn (Vicar) on Nov 05, 2008 at 21:59 UTC

    perl -0777 -pe '$_=reverse;s{>ELBAT/<}{ECALPER};$_=reverse' test.htm

      Are the two reverses (and backward words) better to use than just matching everything before the last </table>?

      perl -0777 -pe 's!(.*)</table>!${1}REPLACE!s;' test.htm

        It depends... How do you compare one JAPH with another?

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://721825]
Approved by ccn
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others browsing the Monastery: (10)
As of 2016-10-21 13:25 GMT
Find Nodes?
    Voting Booth?
    How many different varieties (color, size, etc) of socks do you have in your sock drawer?

    Results (289 votes). Check out past polls.