首页 > 解决方案 > 如何用 Perl 提取某些行?

问题描述

我有这样的字符串

Modified files: ['A', 'B']

File: /tpl/src/vlan/VlanInterfaceValidator.cpp

Newly generated warnings:
A has warnings
B has warning

Status: PASS

我想要“新生成的警告:”的值,应该是

A has warnings
B has warning

我是 perl 新手,不知道如何在 Perl 中使用正则表达式。请帮忙。

标签: perl

解决方案


这种问题你可以阅读到包含你想要的部分的行并且对这些行不做任何事情,然后阅读行直到你想要的东西的开始,保留这些行:

# ignore all these lines
while( <DATA> ) {
    last if /Newly generated warnings/;
    }

# process all these lines
while( <DATA> ) {
    last if /\A\s*\z/;  # stop of the first blank line
    print;  # do whatever you need
    }

__END__
Modified files: ['A', 'B']

File: /tpl/src/vlan/VlanInterfaceValidator.cpp

Newly generated warnings:
A has warnings
B has warning

Status: PASS

那是从文件句柄中读取的。处理字符串非常简单,因为您可以在字符串上打开文件句柄,以便逐行处理字符串:

my $string = <<'HERE';
Modified files: ['A', 'B']

File: /tpl/src/vlan/VlanInterfaceValidator.cpp

Newly generated warnings:
A has warnings
B has warning

Status: PASS
HERE

open my $fh, '<', \ $string;

while( <$fh> ) {
    last if /Newly generated warnings/;
    }

while( <$fh> ) {
    last if /\A\s*\z/;
    print;  # do whatever you need
    }

推荐阅读