Reputation: 509
I need to take the following string and break it into chunks:
[ToNode=cup-subscriber][Reason=Critical service is down][FromNode=cup-publisher][AppID=Cisco UP Server Recovery Manager]
Each chunk is encapsulated in brackets. I'm looking to do this in Perl, and am looking for direction on a method.
Thanks!
Upvotes: 2
Views: 1333
Reputation: 6840
Try this:
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;
Or more verbosely:
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;
Upvotes: 0
Reputation: 455470
You can split at the point between ]
and a [
using lookahead and lookbehind assertions:
$str = '[ToNode=cup-subscriber][Reason=Critical service is down]
[FromNode=cup-publisher][AppID=Cisco UP Server Recovery Manager]';
@pieces = split/(?<=\])(?=\[)/,$str;
Upvotes: 2
Reputation: 1568
Use the /g modifier for regular expressions. Either in list context to extract into an array:
$data = "[ToNode=cup-subscriber][Reason=Critical service is down][FromNode=cup-publisher][AppID=Cisco UP Server Recovery Manager]"
my @chunk = ( $data =~ /\[(.*?)\]/g );
or in a while loop to iterate over the chunks:
$data = "[ToNode=cup-subscriber][Reason=Critical service is down][FromNode=cup-publisher][AppID=Cisco UP Server Recovery Manager]"
while ( $data =~ /\[(.*?)\]/g ) {
process($1);
}
Upvotes: 5