Perl - 搜索字符串

问题描述 投票:0回答:2

我想知道,如果$search不在$content。搜索字符串不应位于h2标记中。

my $search="Hello World";
my $content="<p>Hello World<h2>Is Hello World inside this tag?</h2><p>Thank you";

if ($content !~ /<h2>.*?($search \<\/h2\>)/;) {}

这不起作用。有人有想法吗?

perl
2个回答
0
投票

</h2>没有立即跟随$search。但是在正则表达式中加上.*之后添加.*?$search仍然无法完全解决它,例如它认为以下是“内部”:

my $content="<h2>Is it inside this tag?</h2><p>Thank you Hello World</h2>";

这可能是你想要的:

my $inside;
while ($content =~ m{(<h2>.*?</h2>)}g) {
    my $h2 = $1;
    $inside = 1 if -1 != index $h2, $search;
}
say $inside ? 'yes' : 'no';

但是,通过HTML解析器解析内容会更好。


0
投票

我强烈建议使用正确的HTML解析器;在这里我使用Mojo::DOM,因为它有一个相当现代的界面,但还有其他几个模块可用。

use warnings;
use strict;
use Mojo::DOM;

my $search="Hello World";
my $content="<p>Hello World<h2>Is Hello World inside this tag?</h2><p>Thank you";

my $dom = Mojo::DOM->new($content);
my $found = defined($dom->find('h2')->map('all_text')->first(qr/\Q$search\E/));

print $found ? "Found it\n" : "Didn't find it\n";

__END__

Found it
© www.soinside.com 2019 - 2024. All rights reserved.