我需要使用以下字符串并将其分成块:
[ToNode = cup-subscriber] [原因=关键服务是 down] [FromNode = cup-publisher] [AppID = Cisco UP服务器恢复管理器]
每个块都封装在括号中。我希望在Perl中做到这一点,并且正在寻找方法的方向。
谢谢!
答案 0 :(得分:5)
对正则表达式使用/ g修饰符。在列表上下文中提取到数组中:
$data = "[ToNode=cup-subscriber][Reason=Critical service is down][FromNode=cup-publisher][AppID=Cisco UP Server Recovery Manager]"
my @chunk = ( $data =~ /\[(.*?)\]/g );
或在while循环中迭代块:
$data = "[ToNode=cup-subscriber][Reason=Critical service is down][FromNode=cup-publisher][AppID=Cisco UP Server Recovery Manager]"
while ( $data =~ /\[(.*?)\]/g ) {
process($1);
}
答案 1 :(得分:2)
您可以使用前瞻和后瞻断言在]
和[
之间进行拆分:
$str = '[ToNode=cup-subscriber][Reason=Critical service is down]
[FromNode=cup-publisher][AppID=Cisco UP Server Recovery Manager]';
@pieces = split/(?<=\])(?=\[)/,$str;
答案 2 :(得分:0)
试试这个:
my $str = '[ToNode=cup-subscriber][Reason=Critical service is down][FromNode=cup-publisher][AppID=Cisco UP Server Recovery Manager]';
my %fields = $str =~ m{\[([^][=]+)=([^][=]+)\]}g;
say "$_: $fields{$_}" for sort keys %fields;
或者更详细地说:
my $str = '[ToNode=cup-subscriber][Reason=Critical service is down][FromNode=cup-publisher][AppID=Cisco UP Server Recovery Manager]';
# Capture all occurrences of ...
my %fields = $str =~ m{
\[ # Open bracket
( [^][=]+ ) # Sequence of 1 or more non ][= characters
= # Equals
( [^][=]+ ) # Sequence of 1 or more non ][= characters
\] # Close bracket
}xg;
# Dump contents of %fields
say "$_: $fields{$_}" for sort keys %fields;