与匹配一起提取周围的单词

时间:2010-03-06 06:05:09

标签: regex perl

我正在寻找搜索词的每一个出现,例如ddd,在文件中并输出周围环境,如下所示:

FILE.TXT

aaa bbb ccc ddd eee fff
ttt uuu iii eee ddd
ddd
ggg jjj kkk ddd lll

输出

ccc ddd eee
eee ddd
ddd
kkk ddd lll

作为一个起点,我正在使用这段代码

#!/usr/bin/perl -w     
while(<>) { 
    while (/ddd(\d{1,3}))/g) {       
    print "$1\n"
    }  
} 

4 个答案:

答案 0 :(得分:3)

您可以尝试以下操作..它会提供您想要的输出:

while(<>) {
        if(/((?:\w+ )?ddd(?: \w+)?)/) {
                print "$1\n";
        }
}

使用正则表达式:

(         # open the grouping.
(?:\w+ )? # an optional word of at least one char followed by a space.
ddd       #  'ddd'
(?: \w+)? # an optional space followed by a word of at least one char.
)         # close the grouping.

答案 1 :(得分:1)

#!/usr/bin/perl -w
while (<>) {
    if (/((?:[a-z]{3} )?ddd(?: [a-z]{3})?)/)
        print "$1\n";
}

答案 2 :(得分:1)

while (<>) {  
    chomp;
    my @words = split;
    for my $i (0..$#words) {
        if ($words[$i] eq 'ddd') {
            print join ' ', $i > 0 ? $words[$i-1] : (), $words[$i], $i < $#words ? $words[$i+1] : ();
            print "\n";
        }
    }

}

答案 3 :(得分:-1)

#!/usr/bin/perl

while (<>) {
    chomp;
    @F = split /\s+/;
    if (/^ddd$/) {print $_."\n";next};
    for ($i=0; $i<=$#F;$i++) {
        if ($F[$i] eq 'ddd') {
            print "$F[$i-1] $F[$i] $F[$i + 1]\n";
        }
    }
}