regex - 如何重置 $1 perl 变量?

标签 regex perl

我尝试进行正则表达式匹配:

$address =~ s/$re_region//;
$new_address_h->{ region     } =  $1  //'';

# $1 =  undef; # ERROR: Modification of a read-only value attempted at ...
$address =~ s/$re_city//;
$new_address_h->{ city       } =  $1;

当城市不匹配时,我希望它用undef填充。但是当 city 不匹配时,$1 具有之前匹配的值。为什么?我希望当匹配失败时,它的输出没有值,甚至没有特殊变量。像 eval 刷新 $@

没有额外的 if 是否可行?

最佳答案

记录在案的行为 ( perlvar ):

Perl sets these variables when it has a successful match, so you should check the match result before using them.

您可以使用 do使用三元运算符填充哈希:

$new_address_h->{region} = do { $address =~ s/$re_region// ? $1 : undef };
$new_address_h->{city}   = do { $address =~ s/$re_city//   ? $1 : undef };

或者,用 undefs 填充散列,然后在匹配时用值替换它们:

my $new_address_h = { region => undef, city => undef };
$address =~ s/$re_region// and $new_address_h->{region} = $1;
$address =~ s/$re_city//   and $new_address_h->{city}   = $1;

常见的方式是在列表赋值中只匹配,而不是替换和填充:

($new_address_h->{region}) = $address =~ /$re_region/;
($new_address_h->{city})   = $address =~ /$re_city/;

关于regex - 如何重置 $1 perl 变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60712087/

相关文章:

java - 正则表达式匹配 href 链接并将其替换为 <b> </b>

perl - Perl 的最佳 XSLT 引擎是什么?

string - 使用 PERL 脚本精确匹配和替换文件

perl - 当 my() 有条件时会发生什么?

java - 需要正则表达式的说明(帮助)

regex - 用regexp替换yaml结构中的版本

regex - 在 shell 脚本中使用正则表达式实现多行模式

Perl REST 客户端,身份验证问题

javascript - 正则表达式提取括号内容

regex - R 正则表达式 : issues with character vectors containing NAs