什么是匹配单行与多重匹配的正则表达式?

时间:2010-08-31 15:49:37

标签: perl json

$str = "Data = [ {"name": "test","Address": "UK" "currency": "£" },{"name": "test2","Address": "US" "currency": "$" },{"name": "test","Address": "eur" "currency": "E" }

我想显示所有地址

它不是多行字符串。这一切都是一个字符串

请帮助解决此问题

谢谢, TREE J

4 个答案:

答案 0 :(得分:3)

你的字符串是JSON! Treat it as such

编辑:我是个白痴,无法判断问题被标记为perl而不是PHP :-)链接被修改。

答案 1 :(得分:2)

这应该有效:

while ($str =~ /\"Address\":\S+\"(.*?)\"/g) {
      print "Address = $1\n";
}

答案 2 :(得分:2)

您可以使用适合该作业的工具来完成此操作。在这种情况下,您使用正则表达式修复损坏的JSON,然后使用JSON来获取数据:

#!/usr/bin/perl

use strict;
use warnings;

use JSON;

my $input  = <DATA>;
my ($json) = $input =~ /DATA = (.*)/;
my $data   = decode_json $json;

for my $record (@$data) {
    print "$record->{name} has address $record->{Address}\n";
}

__DATA__
DATA = [ {"name": "test",  "Address": "UK", "currency": "£" }, {"name": "test2", "Address": "US", "currency": "$" }, {"name": "test",  "Address": "eur", "currency": "E" } ]

答案 3 :(得分:0)

类似的东西:

my $str = q(Data = [ {"name": "test","Address": "UK" "currency": "£" },{"name": "test2","Address": "US" "currency": "$" },{"name": "test","Address": "eur" "currency": "E" });
my @addresses = $str =~ /"Address":\s*"([^"]*)"/g;
print "@addresses\n";

HTH,

(PS:发布真实代码,不是伪代码......)