2012-12-03 59 views
0

我有這樣一行:
[Fri Oct 5 09:11 2012] 0.005 [ext2/1/rel 322 (0,50)] [abc] I'm Sure [he/she] is leading CORN @types (countyfair)perl的分裂3號線]用正則表達式

我如何從3]分裂,並有2個部分:

[Fri Oct 5 09:11 2012] 0.005 [ext2/1/rel 322 (0,50)] [abc]  

I'm Sure [he/she] is leading CORN @types (countyfair) 
+1

它是保證是** **最後']'在該行? –

+2

@ m.buettner-不是它不保證。請參閱更新 – mamesaye

回答

4

這一個跳過三個] s:

use strict; 
use warnings; 

while (<>) { 
    if (my ($p1, $p2) = (/([^]]+][^]]+][^]]+])\s*(.*)/)) { 
    print "$p1 : $p2\n"; 
    } 
} 

使用數組:

my @a; 
while (<>) { 
    if (@a = (/([^]]+][^]]+][^]]+])\s*(.*)/)) { 
    print join(",", @a), "\n"; 
    } 
} 
+0

thks 4快速回答。是否可以使用拆分?我正在處理一個數組。 – mamesaye

+1

更新了代碼,以顯示如何使用數組,看着分裂... – perreal

+0

非常感謝你。 – mamesaye

0

我感興趣的是一個通用的功能,所以在這裏它是:

#!/usr/bin/env perl 

use strict; 
use warnings; 

my $str = q{[Fri Oct 5 09:11 2012] 0.005 [ext2/1/rel 322 (0,50)] [abc] I'm Sure [he/she] is leading CORN @types (countyfair)}; #'# fix highlight 

my ($first, $second) = split_after_nth(qr/]/, $str, 3); 
$second =~ s/^\s*//; #/# fix highlight 
print "$first\n$second\n"; 

sub split_after_nth { 
    my ($qr, $str, $num) = @_; 
    my @parts = split /($qr)/, $str, ++$num; 
    my $second = pop @parts; 
    my $first = join '', @parts; 
    return ($first, $second); 
} 
1

一看,後面的三串各由]終止會做訣竅。在第三個]之後,你沒有提到你想處理的空白,所以我把它留在了那裏。

use strict; 
use warnings; 

my $s = q{[Fri Oct 5 09:11 2012] 0.005 [ext2/1/rel 322 (0,50)] [abc] I'm Sure [he/she] is leading CORN @types (countyfair)}; 
my @pair = split /(?:[^]]*\]){3}\K/, $s; 

print "$_\n" for @pair; 

輸出

[Fri Oct 5 09:11 2012] 0.005 [ext2/1/rel 322 (0,50)] [abc] 
I'm Sure [he/she] is leading CORN @types (countyfair)