Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/perl/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Perl 从等号后的字符串中获取哈希中的所有值_Perl - Fatal编程技术网

Perl 从等号后的字符串中获取哈希中的所有值

Perl 从等号后的字符串中获取哈希中的所有值,perl,Perl,我有一个这样的字符串“测试字符串有一个类似于abc=“123”、bcd=“345”的tes值,或者它可以是xyz=“4567”和ytr=“434” 现在我想得到等号后的值。哈希结构如下: $hash->{abc} =123, $hash->{bcd} =345, $hash->{xyz} =4567, 我已经尝试过这个$str=~/(\S+)\S*=\S*(\S+)/xg正则表达式返回捕获的对,这些对可以分配给一个匿名的散列 use warnings 'all'; use s

我有一个这样的字符串
“测试字符串有一个类似于abc=“123”、bcd=“345”的tes值,或者它可以是xyz=“4567”和ytr=“434”

现在我想得到等号后的值。哈希结构如下:

$hash->{abc} =123,
$hash->{bcd} =345,
$hash->{xyz} =4567,

我已经尝试过这个
$str=~/(\S+)\S*=\S*(\S+)/xg

正则表达式返回捕获的对,这些对可以分配给一个匿名的散列

use warnings 'all';
use strict;
use feature 'say';

my $str = 'Test string has tes value like abc="123",bcd="345",or it '
        . 'it can be xyz="4567" and ytr="434"';    

my $rh = { $str =~ /(\w+)="(\d+)"/g }

say "$_ => $rh->{$_}" for keys %$rh ;
印刷品

bcd => 345 abc => 123 ytr => 434 xyz => 4567 bcd=>345 abc=>123 ytr=>434 xyz=>4567
在注释之后–对于
=
符号周围可能的空格,请将其更改为
\s*=\s*

#!/usr/bin/perl
use strict;
use warnings;
use Data::Dumper;
my $string = q{Test string has tes value like abc="123",bcd="345" and xyz="523"};
my %hash = $string =~ /(\w+)="(\d*)"/g;
print Dumper \%hash;
输出

$VAR1 = {
          'xyz' => '523',
          'abc' => '123',
          'bcd' => '345'
        };

您的测试字符串如下所示(稍微编辑以修复引用问题)

我使用此代码测试您的正则表达式:

#!/usr/bin/perl

use strict;
use warnings;
use 5.010;

use Data::Dumper;

my $text = 'Test string has tes value like abc="123",bcd="345",or it it can be xyz="4567" and ytr="434"';

my %hash = $text =~ /(\S+)\s*=\s*(\S+)/g;

say Dumper \%hash;
这将产生以下输出:

$VAR1 = {
          'abc="123",bcd' => '"345",or'
          'ytr' => '"434"',
          'xyz' => '"4567"'
        };
问题是
\S+
匹配任何非空白字符。这太过分了。您需要更详细地描述有效字符

你的钥匙看起来都是字母。您的值都是数字,但它们被不需要的引号字符包围。因此,请尝试使用这个正则表达式=
/([a-z]+)\s*=\s*“(\d+)”/g

这就产生了:

$VAR1 = {
          'bcd' => '345',
          'abc' => '123',
          'ytr' => '434',
          'xyz' => '4567'
        };

在我看来,这是正确的。

那么你到底有什么问题?我认为您要做的是解析字符串,找到所有的
word=“number”
对,并将它们分配给哈希。顺便说一句,您的字符串不是有效的Perl,因为您嵌套了未替换的双引号
”。告诉我们,到目前为止您尝试了什么?它可以用简单的正则表达式来解决。@Developer:好的,那么你所尝试的有什么问题?$VAR1={}$rh中没有数据我们怎么能忽略空格我不明白--忽略什么空格?spaces between abc=“1234”@Developer:你是说你的真实数据中有空格,而你在示例数据中没有向我们展示?如果你的测试数据没有涵盖所有的可能性,你就不能期望得到有用的答案:-)
$VAR1 = {
          'bcd' => '345',
          'abc' => '123',
          'ytr' => '434',
          'xyz' => '4567'
        };