@H_502_1@
我有一个字符串:
<https://gitlab.me.com/api/v3/projects/all?page=2&per_page=5>; rel="next",<https://gitlab.me.com/api/v3/projects/all?page=1&per_page=5>; rel="first",<https://gitlab.me.com/api/v3/projects/all?page=8&per_page=5>; rel="last"
所以格式是
(<val>; rel="key")*
我想用以下格式将其解析为哈希:
next => https://gitlab.me.com/api/v3/projects/all?page=2&per_page=5 first => https://gitlab.me.com/api/v3/projects/all?page=1&per_page=5 last => https://gitlab.me.com/api/v3/projects/all?page=8&per_page=5
在Java中,我将使用正则表达式模式来提取每个键=>价值对并将它们放入地图中.模式将是这样的:
<([^>]++)>;\s*rel="([^"]++)"
哪个会给我第二个匹配组中的键和第一个匹配组中的值.同样的方法是实现这一目标的最好方法是Perl,还是我能做些什么?
附:我使用Perl而不是Java的原因是服务器没有Java.
解决方法
您可以在“,”上拆分字符串,然后使用映射创建哈希:
#!/usr/bin/env perl use strict; use warnings; my $str = 'https://gitlab.me.com/api/v3/projects/all?page=2&per_page=5; rel="next",https://gitlab.me.com/api/v3/projects/all?page=1&per_page=5; rel="first",https://gitlab.me.com/api/v3/projects/all?page=8&per_page=5; rel="last"'; my %hash = map { my ($v,$k) = $_ =~ /\s*([^;]+);\s*rel="([^"]+)".*/; $k => $v; } split ',',$str; foreach my $key (keys %hash) { print "$key => $hash{$key}\n" }
输出:
first => https://gitlab.me.com/api/v3/projects/all?page=1&per_page=5 next => https://gitlab.me.com/api/v3/projects/all?page=2&per_page=5 last => https://gitlab.me.com/api/v3/projects/all?page=8&per_page=5
更新
使用新字符串,您可以:
$str = q(<https://gitlab.me.com/api/v3/projects/all?page=2&per_page=5>; rel="next",<https://gitlab.me.com/api/v3/projects/all?page=1&per_page=5>; rel="first",<https://gitlab.me.com/api/v3/projects/all?page=8&per_page=5>; rel="last"); my %hash = map { my ($v,$k) = $_ =~ /<([^>]+)>;\s*rel="([^"]+)".*/; $k => $v; } split ',$str;
得到相同的结果.