Perl Regex:匹配文本和可选的多行

时间:2013-08-24 11:11:00

标签: regex arrays perl

我正在尝试从Linux Make文件中提取目标文件。以下是一些例子:

Intel E1000E:

e1000e-objs := 82571.o ich8lan.o 80003es2lan.o \
       mac.o manage.o nvm.o phy.o \
       param.o ethtool.o netdev.o ptp.o

Chelsio T3:

cxgb3-objs := cxgb3_main.o ael1002.o vsc8211.o t3_hw.o mc5.o \
       xgmac.o sge.o l2t.o cxgb3_offload.o aq100x.o

Atheros ALX:

alx-objs := main.o ethtool.o hw.o

如何制作一个返回以下内容的正则表达式:=考虑到多行是可选的,可能有两行以上?请注意,反斜杠是Makefile内容的一部分。

我只知道如何手动指定新行的数量,例如:

$obj_files_no_ext = "e1000";
my @filestmp = ($Makefile_contents =~ m/$obj_files_no_ext-objs\s*[\+\:]= (.*)\\\s*\n(.*)/g);

2 个答案:

答案 0 :(得分:2)

您可以尝试使用此模式:

(?>$obj_files_no_ext-objs\s*:=|\G)\s*\K(?>[^\s.]++|\.(?!o(?:\s|$)))++\.o

模式细节:

(?>                    # open an atomic group
    $obj_files_no_ext  # radical
    -objs\s*:=         
  |                    # OR
    \G                 # contiguous match
)                      # close the atomic group
\s*\K                  # optional spaces and reset all the match
(?>                    # open an atomic group (filename possible characters)
    [^\s.]++           # all that is not a white character or a dot (1+ times)
  |                    # OR
    \.(?!o(?:\s|$))    # a dot not followed by "o", a space or the string end 
)++                    # repeat the atomic group one or more times
\.o           

示例:

#!/usr/bin/perl
use strict;
use warnings;

my $Makefile_contents = q{e1000e-objs := 82571.o ich8lan.o 80003es2lan.o 
   mac.o manage.o nvm.o phy.o 
   param.o ethtool.o netdev.o ptp.o};

my $obj_files_no_ext = "e1000e";
my $reg = qr/(?>$obj_files_no_ext-objs\s*:=|\G)\s*\K(?>[^\s.]++|\.(?!o(?:\s|$)))++\.o/;
my @filestmp =  $Makefile_contents =~ /$reg/g;
print join(" ",@filestmp);

答案 1 :(得分:1)

你可以试试这个:

$obj_files_no_ext-objs\s*:=\s*((?:(?:[^\s\\]*?\.o)[\s\n\r\\]*)+)

这将捕获属于组1中某个$obj_files_no_ext的所有目标文件。