开发者

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 u开发者_JS百科tilities for this solution but more so with Perl since I am comfortable with it.


$_ = "[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


\[(.*?)\]

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


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜