in reply to Replace empty alt tag on <img> tag

You can use XML::LibXML:
#!/usr/bin/perl use warnings; use strict; use XML::LibXML; my $input = '<image href = "images/cron1.png"><alt></alt></image>'; my $dom = 'XML::LibXML'->load_xml(string => $input); for my $alt ($dom->findnodes('//image/alt[not(text())]')) { $alt->parentNode->removeChild($alt); } print $dom;

or the less verbose wrapper XML::XSH2:

open file.xml ; rm //image/alt[not(text())] ; save :b ;

map{substr$_->[0],$_->[1]||0,1}[\*||{},3],[[]],[ref qr-1,-,-1],[{}],[sub{}^*ARGV,3]

Replies are listed 'Best First'.
Re^2: Replace empty alt tag on <img> tag
by vlearner (Initiate) on Jan 20, 2022 at 12:06 UTC

    can I do the same with regular expression??

      Generally, no.
      map{substr$_->[0],$_->[1]||0,1}[\*||{},3],[[]],[ref qr-1,-,-1],[{}],[sub{}^*ARGV,3]
        Generally yes, at least since Perl regex are turing complete

        The real question should be: Is it possible with a simple regex?

        Answer: No.

        A regex parsing HTML wouldn't be less complex than a full scale HTML parser and consist of various nested sub expressions.

        Certainly not a one liner.

        - Ron

        > here at the monastery only tybalt89 owns a special permission to deal with HTML or XML using regular expressions

        Agreed that tybalt89 has earned it. To nitpick though, I think TheDamian is also worthy of this special permission.

        The PPR module provides a single regular expression that defines a set of independent subpatterns suitable for matching entire Perl documents

        -- from PPR by TheDamian (as if you couldn't guess ;-)

        See also these comments by kcott and haukex, discussing the differences between PPR and PPI.