2

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!

1
  • @chunks = split /(?:\]|^)(?:\[|$)/, $string for a rather quick and dirty solution. Commented Sep 26, 2012 at 13:54

3 Answers 3

5

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);
}
Sign up to request clarification or add additional context in comments.

Comments

2

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;

See it

1 Comment

This is the one I used. Thank you!
0

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;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.