html - 如何使用 Perl 正则表达式删除未使用的嵌套 HTML span 标记?

标签 html regex perl

我正在尝试从 HTML 文件中删除未使用的跨度(即没有属性的跨度),已经用其他正则表达式清除了我不需要的所有属性。

我的正则表达式没有选择要删除的正确的开始和结束标记对时出现问题。

my $a = 'a <span>b <span style="color:red;">c</span> d</span>e';
$a =~ s/<span\s*>(.*?)<\/span>/$1/g;
print "$a\

返回

a b <span style="color:red;">c d</span>e

但我希望它返回

a b <span style="color:red;">c</span> de

感谢帮助。

最佳答案

尝试 HTML::Parser :

#!/usr/bin/perl

use strict;
use warnings;

use HTML::Parser;

my @print_span;
my $p = HTML::Parser->new(
  start_h   => [ sub {
    my ($text, $name, $attr) = @_;
    if ( $name eq 'span' ) {
      my $print_tag = %$attr;
      push @print_span, $print_tag;
      return if !$print_tag;
    }
    print $text;
  }, 'text,tagname,attr'],
  end_h => [ sub {
    my ($text, $name) = @_;
    if ( $name eq 'span' ) {
      return if !pop @print_span;
    }
    print $text;
  }, 'text,tagname'],
  default_h => [ sub { print shift }, 'text'],
);
$p->parse_file(\*DATA) or die "Err: $!";
$p->eof;

__END__
<html>
<head>
<title>This is a title</title>
</head>
<body>
<h1>This is a header</h1>
a <span>b <span style="color:red;">c</span> d</span>e
</body>
</html>

关于html - 如何使用 Perl 正则表达式删除未使用的嵌套 HTML span 标记?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/667130/

相关文章:

html - 如何为所有子元素设置一个 css 类? ( Angular 6,Ngx Bootstrap )

jQuery 启用防止默认并为列表中的第一个 child 切换事件类

perl - Selenium::Remote::Driver 捕获错误

regex - 哪些字符可以用作正则表达式分隔符?

linux - 在 Perl 中从管道读取无缓冲数据

javascript - 文件上传完成删除文件名?

javascript - 根据javascript中数组中的数据显示元素

regex - str_extract_all 返回不匹配的组

regex - python regex 如何避免匹配多个分号?

java - Spring验证java模式多邮件