Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the regex for this array

Tags:

regex

perl

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
like image 703
dania Avatar asked Apr 26 '26 11:04

dania


2 Answers

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] }
like image 56
Eugene Yarmash Avatar answered Apr 29 '26 02:04

Eugene Yarmash


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
like image 36
TLP Avatar answered Apr 29 '26 01:04

TLP



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!