2014-09-18 54 views
0

我有一個文件數組。用的幾行文字的每個文件,在外面我試圖打通的regex幾個特定字符串在Perlperl:讀取文件時的正則表達式

use strict; 
use warnings; 

foreach my $myfile (@myFiles) { 
    open my $FILE, '<', $myfile or die $!; 
    while (my $line = <$FILE>) { 
     my ($project, $value1, $value2) = <Reg exp>, $line; 
     print "Project : $1 \n"; 
     print "Value1 : $2 \n"; 
     print "Value2 : $3 \n"; 
    } 
    close(FILE); 
} 

*文件內容*

Checking Project foobar 
<few more lines of text here> 
Good Files excluding rules:  15 - 5% 
Bad Files excluding rules: 270 - 95% 

<one more line of text here> 
Good Files including rules:  15 - 5% 
Bad Files including rules: 272 - 95% 
<few more lines of text here> 

*所需的輸出*

Project:foobar 
Value1 : Good Files excluding rules:  15 - 5% 
      Bad Files excluding rules: 270 - 95% 
Value2 : Good Files including rules:  15 - 5% 
      Bad Files including rules: 272 - 95% 
+0

'打開我的$ FILE, '<',$ MYFILE死$';;缺少$ myfile'和'die'之間'一個'或'! – 2014-09-18 20:23:01

+0

@JimDavis謝謝,更新 – Jill448 2014-09-18 20:48:08

+0

這些行是嚴格的順序,如「好/壞排除」,然後「好/壞包括」,或者他們是否有序和可能交錯?另外,我還沒有跟上Perl,這是',$ line'一個新的構造? – sln 2014-09-18 21:44:32

回答

1

這是不值得嘗試創建一個單一的正則表達式來捕獲所有你想要的值。

取而代之,只需逐行處理,然後爲每個要匹配的行類型創建一個正則表達式。

use strict; 
use warnings; 

my $fh = \*DATA; 

my $counter = 0; 

while (<$fh>) { 
    if (/Checking Project (\w+)/) { 
     printf "Project:%s\n", $1; 

    } elsif (/^Good Files/) { 
     printf "Value%-2s: %s", ++$counter, $_; 

    } elsif (/^Bad Files/) { 
     printf "  : %s", $_; 
    } 
} 

__DATA__ 
Checking Project foobar 
<few more lines of text here> 
Good Files excluding rules:  15 - 5% 
Bad Files excluding rules: 270 - 95% 

<one more line of text here> 
Good Files including rules:  15 - 5% 
Bad Files including rules: 272 - 95% 
<few more lines of text here> 

輸出:

Project:foobar 
Value1 : Good Files excluding rules:  15 - 5% 
     : Bad Files excluding rules: 270 - 95% 
Value2 : Good Files including rules:  15 - 5% 
     : Bad Files including rules: 272 - 95% 
1

您可以使用類似這樣的正則表達式:

(good.*|bad.*) 

Working demo

enter image description here

匹配信息

MATCH 1 
1. [54-95] `Good Files excluding rules:  15 - 5%` 
MATCH 2 
1. [96-136] `Bad Files excluding rules: 270 - 95%` 
MATCH 3 
1. [167-208] `Good Files including rules:  15 - 5%` 
MATCH 4 
1. [209-249] `Bad Files including rules: 272 - 95%` 

使用上述正則表達式,你可以捕捉你所需要的線。然後你必須添加一些邏輯來產生你想要的輸出。