2011-08-20 110 views
3

比方说,我有文字的身体像这样,这是什么阵正则表达式

["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

正则表达式和数组不走在一起。 – BoltClock

+1

为什么你不会使用JSON http://search.cpan.org/~makamaka/JSON-2.53/lib/JSON.pm? – hsz

回答

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] } 
+0

@dania欢迎您。 –

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