如何在某些单词之前匹配多行

时间:2016-11-30 17:59:29

标签: regex perl

我想提取仅由" FOO BAR"在一些会议成绩单中。

对话有时会传播到多行,我不知道如何提取多行文字。

我认为这可能与使用带有大写字母和冒号的范围运算符的人名相关,但我自己也无法弄清楚这一点。

my $word = 'FOO BAR';

while (<DATA>) {
    print if /\b$word\b/i .. /[A-Z]:/
}


__DATA__
FOO BAR: Good morning. 
I want to meet you later.
JONE DOE: Good morning
FOO BAR: Thank you.
See you later.
JANE DOE: Thank you.
See you later.

输出

FOO BAR: Good morning. 
FOO BAR: Thank you.

1 个答案:

答案 0 :(得分:1)

设置标志。当您找到要查找的名称时将其打开。当您找到其他名称时将其关闭。仅在标志打开时打印。

use strict;
use warnings;

my $word = 'FOO BAR';
my $spew;

while (<DATA>) {
    if (/^([A-Z ]+):/) {
        $spew = $1 eq $word;
    }

    print if $spew;
}

__DATA__
FOO BAR: Good morning.
I want to meet you later.
JONE DOE: Good morning
FOO BAR: Thank you.
See you later.
JANE DOE: Thank you.
See you later.

输出:

FOO BAR: Good morning.
I want to meet you later.
FOO BAR: Thank you.
See you later.