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

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
[ambrus]: 1nickg: obviously the gamers don't know. but anyway, I need the whole room backlit, because watching a monitor in a dark room (like many people do) is tiring for my eyes, even more so than doing it in a lit room.
[1nickt]: ambrus I agree. I suspect one's eyes are always trying to adjust across the boundary between very bright and very dark ... like a camera's autofocus struggling to choose the target.

How do I use this? | Other CB clients
Other Users?
Others chilling in the Monastery: (12)
As of 2017-03-27 14:00 GMT
Find Nodes?
    Voting Booth?
    Should Pluto Get Its Planethood Back?

    Results (320 votes). Check out past polls.