Perl 正则表达式的麻烦

Perl regular expressions troubles

我有一个包含字符串的变量 $rowref->[5]

"  1.72.1.13.3.5  (ISU)"

我正在使用 XML::Twig 构建修改一个 XML 文件,此变量包含某物的版本号信息。所以我想去掉空格和 (ISU)。我尝试使用替换和 XML::Twig 来设置属性:

$artifact->set_att(version=> $rowref->[5] =~ s/([^0-9\.])//g)

有趣的是,我在输出中得到的是

<artifact [...] version="9"/>

我不明白我做错了什么。我用 regular expression tester 检查了一下,似乎没问题。有人可以发现我的错误吗?

s/// 的 return 值是 它所做的替换次数 ,在你的情况下是 9。如果你至少使用 perl 5.14、在替换中加入r标志:

If the "/r" (non-destructive) option is used then it runs the substitution on a copy of the string and instead of returning the number of substitutions, it returns the copy whether or not a substitution occurred. The original string is never changed when "/r" is used. The copy will always be a plain string, even if the input is an object or a tied variable.

否则,通过这样的临时变量:

my $version = $rowref->[5];
$version =~ s/([^0-9\.])//g;
$artifact->set_att(version => $version);

正则表达式替换改变了 varialbe 但 returns 它所做的替换次数(1 没有 /g 修饰符,如果成功的话)。

my $str = 'words 123';
my $ret = $str =~ s/\d/numbers/g;
say "Got $ret. String is now: $str";

您可以先进行替换,$rowref->[5] =~ s/...//;,然后使用更改后的变量。