我有这句话:
[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)
如何将其从 3rd] 拆分并分为两部分:
[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)
答案 0 :(得分:4)
这个跳过三个]
:
use strict;
use warnings;
while (<>) {
if (my ($p1, $p2) = (/([^]]+][^]]+][^]]+])\s*(.*)/)) {
print "$p1 : $p2\n";
}
}
使用数组:
my @a;
while (<>) {
if (@a = (/([^]]+][^]]+][^]]+])\s*(.*)/)) {
print join(",", @a), "\n";
}
}
答案 1 :(得分: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)
答案 2 :(得分: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);
}