【问题标题】:What is the regex for this array这个数组的正则表达式是什么
【发布时间】:2011-10-31 06:30:42
【问题描述】:

假设我有这样的正文

["What Color",["Red","Blue","Green","Yellow","Brown","White"]]

匹配颜色的正则表达式是什么

我试试这个

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

谁能帮我把这个 perl 脚本打印出来

- 你的颜色是:红色 - 你的颜色是:蓝色 - 你的颜色是:绿色 - 你的颜色是:黄色 - 你的颜色是:棕色 - 你的颜色是:白色

【问题讨论】:

标签: regex perl


【解决方案1】:

由于此文本是有效的 json 字符串,您可以使用 JSON 解析它:

use JSON;  

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

【讨论】:

    【解决方案2】:

    除了是一个有效的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
    

    【讨论】:

      猜你喜欢
      • 2012-01-26
      • 1970-01-01
      • 2012-05-07
      • 1970-01-01
      • 2014-07-13
      • 2012-04-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多