其他人已经指出您希望/s 选项使. 匹配换行符,以便您可以使用.* 跨越逻辑行边界。你可能还想要非贪婪的.*?:
use v5.10;
my $html = <<'HTML';
<td class="fieldLabel" height="18">Activation Date:</td>
<td class="dataEntry" height="18">
10/27/2011
</td>
HTML
my $regex = qr|
<td.*?>Activation \s+ Date:</td>
\s*
<td.*?class="dataEntry".*?>\s*
(\S+)
\s*</td>
|xs;
if ( $html =~ $regex ) {
say "matched: $1";
}
else {
say "mismatched!";
}
(2020 年更新)但我会使用 Mojo::DOM 和 CSS 选择器来获取日期。特定的选择器可能依赖于完整的 HTML 源代码,但思路是一样的:
use v5.10;
use Mojo::DOM;
use Mojo::Util qw(trim);
my $html = <<'HTML';
<td class="fieldLabel" height="18">Activation Date:</td>
<td class="dataEntry" height="18">
10/27/2011
</td>
HTML
my $dom = Mojo::DOM->new( $html );
my $date = trim( $dom->at( 'td.dataEntry' )->all_text );
say "Date is $date";
如果你有完整的表格,使用知道如何解析表格的东西会更容易。让诸如 There's also HTML::TableParser 之类的模块处理所有细节:
use v5.10;
my $html = <<'HTML';
<table>
<tr>
<td class="fieldLabel" height="18">Activation Date:</td>
<td class="dataEntry" height="18">
10/27/2011
</td>
</tr>
</table>
HTML
use HTML::TableParser;
sub row {
my( $tbl_id, $line_no, $data, $udata ) = @_;
return unless $data->[0] eq 'Activation Date';
say "Date is $data->[1]";
}
# create parser object
my $p = HTML::TableParser->new(
{ id => 1, row => \&row, }
{ Decode => 1, Trim => 1, Chomp => 1, }
);
$p->parse( $html );
还有HTML::TableExtract:
use v5.10;
my $html = <<'HTML';
<table>
<tr>
<td class="fieldLabel" height="18">Activation Date:</td>
<td class="dataEntry" height="18">
10/27/2011
</td>
</tr>
</table>
HTML
use HTML::TableExtract;
my $p = HTML::TableExtract->new;
$p->parse( $html );
my $table_tree = $p->first_table_found;
my $date = $table_tree->cell( 0, 1 );
$date =~ s/\A\s+|\s+\z//g;
say "Date is $date";