2011-08-20 122 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