开发者

What is the regex for this array

开发者 https://www.devze.com 2023-03-29 06:29 出处:网络
Let\'s say i have a body of text like this [\"What Color\",[\"Red\",\"Blue\",\"Gre开发者_如何学Pythonen\",\"Yellow\",\"Brown\",\"White\"]]

Let's say i have a body of text like this

["What Color",["Red","Blue","Gre开发者_如何学Pythonen","Yellow","Brown","White"]]

What is the regex to match a color

i try this

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

Can someone help me this perl scripts should print

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


As this text is a valid json string, you can parse it with JSON:

use JSON;  

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


Besides being a valid JSON string, it is also a valid perl structure, which can be extracted by evaluating the string. This may not be practical (or safe!) for all the strings out there, but for this particular one, it works:

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);

Output:

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
0

精彩评论

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