2011-04-12 59 views
0

我想重複的比賽在一文中,我想匹配以數字開頭,然後一個製表符塊。正則表達式 - 匹配到下一場比賽

我開始比賽是^\d+\t,但有什麼辦法,以表明我想包括這場比賽,直到下一場比賽的所有文字?

輸入數據:

1  111.111.111.111 
111.111.111.111 
        Host IP  111.111.111.111 
111.111.111.111 
111.111.111.111   Host IP  TCP    app  11111, 11111, 11111, 11111  Allow 
2  111.111.111.111 
111.111.111.111 
111.111.111.111   Host IP  111.111.111.111 
111.111.111.111   Host IP  TCP    app  11111, 11111, 11111, 11111  Allow 
3  111.111.111.111 
111.111.111.111   Host IP  111.111.111.111 
111.111.111.111 
111.111.111.111 
111.111.111.111   Host IP  TCP    app  11111, 11111, 11111, 11111  Allow 
4  111.111.111.111 
111.111.111.111 
111.111.111.111 
111.111.111.111   Host IP  111.111.111.111 
111.111.111.111   Host IP  TCP    app  11111, 11111, 11111, 11111  Allow 

我使用Perl。

+0

文字我試圖解析:http://pastebin.com/rfP8ftsh – mphuie 2011-04-12 19:54:29

回答

1

下面的正則表達式應該做你想要什麼:

^\d+\t(?:[^\d]+|[\d]+(?!\t))* 

這將匹配某些號碼的數字後按Tab,然後被後面沒有標籤的任何數量的非數字字符或數字。

my @matches = $data =~ /^\d+\t(?:[^\d]+|[\d]+(?!\t))*/mg; 

編輯:好吧,這應該工作!

+0

我嘗試過了,它從開始到結束爲一個整體塊匹配。 文字在這裏:http://pastebin.com/rfP8ftsh – mphuie 2011-04-12 19:57:22

+0

@mphuie:最新的編輯應該工作,以前的編輯把它弄壞了,當我試圖以確保它工作時的字符串以數字結束了,哎呀! – 2011-04-12 22:10:00

0

可能是這樣嗎?

/^\d+\t.*?(?:\z|^\d+\t)/ms 
0
while (/ 
    \G 
    (\d+\t) 
    ((?: (?! \d+\t) .)*) 
/xg) { 
    print("match: $1\n"); 
    print("buffer: $2\n"); 
} 
0

樣品輸入和預期的結果會有所幫助,因爲它是我真的不知道我知道你在找什麼。

如果你對一個模式,就像你匹配可能能夠分割字符串:

my $string = "text\n1\ttest\n2\tend\n"; 
my @matches = split /^(\d+)\t/m, $string; 
shift @matches; # remove the text before the first number 
print "[$_]\n" for @matches; 

__END__ 
Output: 
[1] 
[test 
] 
[2] 
[end 
] 

如果匹配多個模式Perl有特殊變量,可以讓你找到一個地方比賽開始和結束。哪些可以用來提取兩場比賽之間的比賽。

use English qw(-no_match_vars); 

my $string = "1\ttestEND\n2\ttextEND\n"; 
if ($string =~ /^\d+\t/) { 
    my $last_match_end = $LAST_MATCH_END[0]; 

    if ($string =~ /END/cg) { 
     my $last_match_start = $LAST_MATCH_START[0]; 
     my $len = $last_match_start - $last_match_end; 
     print substr($string, $last_match_end, $len) . "\n" 
    } 
} 
__END__ 
Output: 
test 
相關問題