如何在正则表达式中将 $1 与数字连接 [英] How to concatenate $1 with number in a regex
问题描述
我想在两个模式之间插入数字:
I would like to insert the number between two patterns:
$s = 'id="" value="div"';
$s =~ s/(id=")(".*)/$1123$2/;
当然,我得到了错误和 " value="div" 结果.预期结果是 id="123" value="div".
Of course I got the error and " value="div" as a result. The expected result is id="123" value="div".
在替换中,我的意思是 1 美元,然后是数字 123,然后是 2 美元,但不是 1123 美元,然后是 2 美元.正则表达式中的正确替换是什么?我想用一个正则表达式来完成.
In the replacement I meant $1, then number 123 and then $2, but not $1123 and then $2. What is the correct replacement in the regex? I would like to do it in one single regex.
谢谢.
推荐答案
$s =~ s/(id=")(".*)/$1123$2/; # Use of uninitialized value $1123 in concatenation (.) or string
尽管您希望它替代 $1
,但 perl 将其视为变量 $1123
.Perl 无法知道您的意思是 $1
.因此,您需要将 variablisation 限制为 $1
,将其指定为 ${1}
:
Though you expected it to substitute for $1
, perl sees it as the variable $1123
. Perl has no way to know that you meant $1
. So you need to limit the variablisation to $1
by specifying it as ${1}
:
$s =~ s/(id=")(".*)/${1}123$2/;
在脚本顶部包含以下内容始终是个好主意.它们将为您节省大量时间和精力.
It is always a good idea to include the following at the top of your scripts. They will save you a lot of time and effort.
use strict;
use warnings;
例如,运行包含上述模块的脚本会导致错误消息:
For example, running your script with the above modules included results in the error message:
Use of uninitialized value $1123 in concatenation (.) or string at /tmp/test.pl line 7.
(忽略报告的脚本名称和行号.)它清楚地说明了 perl 的预期.
(Disregard the reported script name and line numbers.) It clearly states what perl expected.
另一种使用后视和前瞻断言的方法:
Another approach using look-behind and look-ahead assertions:
$s =~ s/(?<=id=")(?=")/123/;
这篇关于如何在正则表达式中将 $1 与数字连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!