我有一个多行字符串,看起来像:
value1: [
2018
],
value2: [ 2019
],
当可能存在可变数量的空格和数字周围的换行符时,我如何才能获取两个方括号之间的value1的数字?有一个简单的正则表达式,还是我应该删除所有的空格然后搜索?
它看起来像一些'伪json'。存在JSON::Relaxed模块,它可以解析这些数据。从文档中,
字符串可以用单引号或双引号引用。无空间字符串也被解析为字符串。
use 5.014;
use warnings;
use JSON::Relaxed 'from_rjson';
my $rstr = do { local $/; <DATA> }; # load the json-like data
my $d = from_rjson( '{' . $rstr . '}' ); # make a hash and parse
say $d->{value2}->[0]; # 2019
__DATA__
value1: [
2018
],
value2: [ 2019
],
当然,样本数据非常小,也许完整集合不能用上述模块解析。
https://regex101.com/r/n2VLSO/2
/^value\d+[:\w ]*\[\s*?(\d+)\s*?\]/gm
我不知道为什么这会在没有评论的情况下获得如此多的负面投票。这很简单,答案不需要是主要或超级解释。如果您认为它不起作用,请自行运行(https://ideone.com/OPV8no):
#!/usr/bin/perl
use 5.014;
use strict;
use warnings;
# Example of string setup
my $str = qq{
value1: [
2018
],
value2: [ 2019
],
};
# Iterate over string and store desired values
my $search_values = [1,2];
my $matches = {};
foreach my $number (@$search_values){
if ($str =~ m/^value${number}[:\w ]*\[\s*?(\d+)\s*?\]/gm){
$matches->{qq{value$number}} = $1;
}
}
# Example of result
use Data::Dumper;
say Dumper($matches);
所以,$matches->{'value1'}
会产生2018