Beefy Boxes and Bandwidth Generously Provided by pair Networks
more useful options
 
PerlMonks  

Match last instance of pattern

by techie411 (Acolyte)
on Nov 05, 2008 at 21:41 UTC ( [id://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 (Saint) 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?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others perusing the Monastery: (3)
As of 2024-04-25 09:23 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found