基于条件的perl正则表达式提取

时间:2013-09-13 20:50:26

标签: regex perl

我正在研究一个框架,我必须得到一些正则表达式,但此时却被卡住了。

Execution start time 09/13/2013 02:43:55 pm

[Case-Url] - www.google.com


[Req-URL ] - www.qtp.com


***Passed***
__________________________________________________________

[Case-Url] - www.yahoo.com


[Req-URL ] - www.msn.com


***Passed***

___________________________________________________________

[Case-Url] - www.google.com


[Req-URL ] - www.qtp.com


***Failed***

在上面的测试结果中,我必须为Passed和Failed测试用例获取[Case-URL]和[Req-URL]。如何仅获取传递结果的Case-URL和Req-URL?

3 个答案:

答案 0 :(得分:1)

正则表达式在这里并不十分合适。相反,将输入拆分为您单独解析的块:

use strict; use warnings; use feature 'say';

<DATA>; # discard first line;
# set record separator
local $/ = "__________________________________________________________\n";
while (my $chunk = <DATA>) {
  my ($case, $req, $statusline) = split /\n/, $chunk;
  # possibly parse $case and $req further here
  if ($statusline =~ /Passed/) {
    say for $case, $req;
  }
}

__DATA__
Execution start time 09/13/2013 02:43:55 pm
[Case-Url] - www.google.com
[Req-URL ] - www.qtp.com
***Passed***
__________________________________________________________
[Case-Url] - www.yahoo.com
[Req-URL ] - www.msn.com
***Passed***
___________________________________________________________
[Case-Url] - www.google.com
[Req-URL ] - www.qtp.com
***Failed***

输出将是:

[Case-Url] - www.google.com
[Req-URL ] - www.qtp.com
[Case-Url] - www.yahoo.com
[Req-URL ] - www.msn.com

答案 1 :(得分:0)

这将提取失败的案例。然后,您可以轻松地从$fifo[0]$fifo[3]中提取Case-Url和Req-Url。对于通过案件也可以这样做。

#!/usr/bin/perl 

use strict;
use warnings;

my @fifo=('') x 7; # Initialize an empty array with size = 7 (Message Block Size)
open(FILE,"temp.txt");

while(<FILE>)
{
    push(@fifo,$_);       # Add element to the end of array making its size 6  
    shift @fifo;          # Remove first element reverting its size back to 5  
    if($fifo[6]=~/Failed/) # Check if 7th line of block has Failed in it 
    {
        print @fifo;
    }
}
close(FILE);

答案 2 :(得分:0)

除了这个特定应用程序的正则表达式的适用性,这里是一个正则表达式,将捕获传递的URL:

\([Case-Url\] - .*)\n+(\[Req-URL \] - (.*)\n+\*{3}Passed\*{3}

我无法在regexplanet中以Perl模式使用此功能,但您可以在Rubular here

中看到它的运行情况