3

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

["What Color",["Red","Blue","Green","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
2

2 Answers 2

6

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] }
Sign up to request clarification or add additional context in comments.

Comments

3

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.