繁体   English   中英

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

[英]Get all values in a hash from string after equals sign Perl

我有一个这样的字符串"Test string has tes value like abc="123",bcd="345",or it it can be xyz="4567" and 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

在注释之后 - 对于=符号周围可能的空格,将其更改为\\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'
        };

演示

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

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

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

#!/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+匹配任何非空白字符。 这太多了。 您需要对有效字符进行更多描述。

你的钥匙似乎都是字母。 您的值都是数字 - 但它们被您不想要的引号字符包围。 所以试试这个正则表达式 = /([az]+)\\s*=\\s*"(\\d+)"/g

这给出了:

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

这对我来说是正确的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM