这个数组的正则表达式是什么?

时间:2011-08-20 16:11:48

标签: regex perl

假设我有一个像这样的文本

["What Color",["Red","Blue","Green","Yellow","Brown","White"]]

匹配颜色的正则表达式是什么

我试试这个

 while ($mystring =~ m,/"(.*?)"/|,|[/"(.*?)"|,|/],g);
 print "Your Color is : [$1]\n";

有人可以帮我这个perl脚本应该打印

 - Your Color is: Red
 - Your Color is: Blue
 - Your Color is: Green
 - Your Color is: Yellow
 - Your Color is: Brown
 - Your Color is: White

2 个答案:

答案 0 :(得分:6)

由于此文本是有效的json字符串,因此您可以使用JSON解析它:

use JSON;  

my $json = '["What Color",["Red","Blue","Green","Yellow","Brown","White"]]';
print "- Your Color is: $_\n" for @{ decode_json($json)->[1] }

答案 1 :(得分:3)

除了是有效的JSON字符串之外,它还是一个有效的perl结构,可以通过计算字符串来提取它。对于那里的所有字符串,这可能不实用(或安全!),但对于这个特定的字符串,它可以工作:

use strict;
use warnings;
use feature qw(say);

my $h = eval("['What Color',['Red','Blue','Green','Yellow','Brown','White']]");
my $tag = $h->[0];
my @colors = @{$h->[1]};
say "- Your '$tag' is: $_" for (@colors);

<强>输出:

C:\perl>tx.pl
- Your 'What Color' is: Red
- Your 'What Color' is: Blue
- Your 'What Color' is: Green
- Your 'What Color' is: Yellow
- Your 'What Color' is: Brown
- Your 'What Color' is: White
相关问题