syker
syker

Reputation: 11302

Pattern Matching and Regex in Perl

I have a list of words that appear in the following format [bmw,32][cadillac,64]. How do I use regex in a Perl script to extract the content in between each set of brackets so that I can print them out in the format I want? I am also interested in using command line utilities for this solution but more so with Perl since I am comfortable with it.

Upvotes: 1

Views: 277

Answers (3)

ajwood
ajwood

Reputation: 19057

my $s = "[bmw,32][cadillac,64]";
$s =~ /\[(.*)\]\[(.*)\]/;
print $1;
print $2;

Upvotes: -1

tchrist
tchrist

Reputation: 80443

$_ = "[bmw,32][cadillac,64][audi,144][toyata,6]";
%car = m{ \s* \[ ( \pL+ ) , ( \pN+ ) \] \s* }gx;
printf "%-10s => %3d\n", $_ => $car{$_} for sort keys %car;
__END__
audi       => 144
bmw        =>  32
cadillac   =>  64
toyata     =>   6

Upvotes: 3

masher
masher

Reputation: 4116

\[(.*?)\]

Non-greedy matching will give you your two tokens. This also assumes that there a no square brackets in the tokens you're matching.

Upvotes: 0

Related Questions