[英]Perl regular expressions troubles
I have a variable $rowref->[5]
which contains the string: 我有一个变量
$rowref->[5]
,其中包含字符串:
" 1.72.1.13.3.5 (ISU)"
I am using XML::Twig
to build modify an XML file and this variable contains the information for the version number of something. 我正在使用
XML::Twig
来构建修改XML文件,并且此变量包含某物的版本号信息。 So I want to get rid of the whitespaces and the (ISU). 因此,我想摆脱空白和(ISU)。 I tried to use a substitution and
XML::Twig
to set the attribute: 我尝试使用替换和
XML::Twig
设置属性:
$artifact->set_att(version=> $rowref->[5] =~ s/([^0-9\.])//g)
Interestingly what I got in my output was 有趣的是,我的输出是
<artifact [...] version="9"/>
I don't understand what I am doing wrong. 我不明白我在做什么错。 I checked with a regular expression tester and it seems fine.
我用正则表达式测试器检查过,看起来还不错。 Can somebody spot my error?
有人可以发现我的错误吗?
The return value of s///
is the number of substitutions it made , which in your case is 9. If you are using at least perl 5.14, add the r
flag to the substitution: s///
的返回值是它进行的替换数目 ,在您的情况下为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.
如果使用“ / r”(非破坏性)选项,则它将在字符串的副本上运行替换,并且不返回替换数,而是返回副本(无论是否发生替换)。 The original string is never changed when "/r" is used.
使用“ / r”时,原始字符串永远不会更改。 The copy will always be a plain string, even if the input is an object or a tied variable.
即使输入是对象或绑定变量,该副本也始终是纯字符串。
Otherwise, go through a temporary variable like this: 否则,请经过这样的临时变量:
my $version = $rowref->[5];
$version =~ s/([^0-9\.])//g;
$artifact->set_att(version => $version);
The regex substitution changes the varialbe in place but returns the number of substitutions it made ( 1
without the /g
modifier, if it was succesful). 该正则表达式替换改变varialbe到位但返回它制成取代数目(
1
无/g
改性剂,如果是成功的)。
my $str = 'words 123';
my $ret = $str =~ s/\d/numbers/g;
say "Got $ret. String is now: $str";
You can do the substitution first, $rowref->[5] =~ s/...//;
您可以先进行替换,
$rowref->[5] =~ s/...//;
, and then use the changed variable. ,然后使用更改后的变量。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.