我需要获取以下字符串并将其分成块:
[ToNode=cup-subscriber][Reason=Critical service is down][FromNode=cup-publisher][AppID=Cisco UP Server Recovery Manager]
每个块都封装在括号中。我正在寻找在 Perl 中执行此操作,并且正在寻找一种方法的方向。
谢谢!
对正则表达式使用 /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);
}
您可以在使用前瞻和后瞻断言之间]
进行拆分:[
$str = '[ToNode=cup-subscriber][Reason=Critical service is down]
[FromNode=cup-publisher][AppID=Cisco UP Server Recovery Manager]';
@pieces = split/(?<=\])(?=\[)/,$str;
试试这个:
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;