繁体   English   中英

使用Perl正则表达式查找和提取多行匹配

[英]Using Perl regex to find and extract matches over multiple lines

我有一个包含以下格式的数百个术语的文本文件:

[Term]  
id: id1  
name: name1  
xref: type1:aab  
xref: type2:cdc  

[Term]  
id: id2  
name: name2  
xref: type1:aba  
xref: type3:fee 

我需要使用类型1的外部参照提取所有术语,并将它们以相同的格式写入新文件。 我打算使用这样的正则表达式:

/\[Term\](.*)type1(.*)[^\[Term\]]/g

找到相应的术语但我不知道如何在多行上搜索正则表达式。 我应该将原始文本文件读作字符串还是行? 任何帮助将非常感谢。

试试这个正则表达式:

/(?s)\[Term\].*?xref: type1.*?(?=\[Term\])/g

这个正则表达式有以下显着的变化:

  • (?s)打开“点匹配换行符”
  • .*? 是一种非贪婪的表达方式。 使用.*将消耗文件中最后一个[Term]的所有内容
  • 删除了不必要的分组.*?
  • 添加了轻微的细化以匹配外部参照 ,而不仅仅是在任何地方输入1
  • 删除了以下Term标记的错误语法
  • 添加了一个前瞻性的匹配,但不包括下一个[Term]标记

一种不同的方法可能是使用$/ variable在空行中拆分块,因为每个块用换行符分割它,然后为每一行运行一个正则表达式。所以当其中一个匹配打印并读取下一个块时。 一个单行的例子:

perl -ne '
    BEGIN { $/ = q|| }
    my @lines = split /\n/;  
    for my $line ( @lines ) {
        if ( $line =~ m/xref:\s*type1/ ) {     
            printf qq|%s|, $_;
            last;
        }
    }
' infile

假设输入文件如下:

[Term]
id: id1
name: name1
xref: type1:aab
xref: type2:cdc

[Term]
id: id2
name: name1
xref: type6:aba
xref: type3:fee

[Term]
id: id2
name: name1
xref: type1:aba
xref: type3:fee

[Term]
id: id2
name: name1
xref: type4:aba
xref: type3:fee

[Term]  
id: id2  
name: name1  
xref: type1:aba  
xref: type3:fee

它产生:

[Term]  
id: id1  
name: name1  
xref: type1:aab  
xref: type2:cdc  

[Term]  
id: id2  
name: name1  
xref: type1:aba  
xref: type3:fee 

[Term]  
id: id2  
name: name1  
xref: type1:aba  
xref: type3:fee

如您所见,只打印那些带有xref: type1行的那些。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM