[英]How can i change a substring in a matched string in a file in perl
我想要以下更改:
原版的 :
Format="%05dA1"
StartValue="2"
Format="%05dB1"
StartValue="2"
Format="%05dC1"
StartValue="2"
改性:
Format="%05dA2"
StartValue="2"
Format="%05dB2"
StartValue="2"
Format="%05dC2"
StartValue="2"
我尝试了以下正则表达式,但无法获得所需的内容。
$main_course =~ s/05d\w{2}\d{1}/05d\w{2}$name/g
我担心人们为此感到挣扎。 如果您正在运行Perl 5版本10或更高版本(应该是因为它已经使用了5年以上),则可以有用地使用\\K
顺序,在进行替换时, K会将任何内容保留在左侧。
use strict;
use warnings;
while (<DATA>) {
s/%05[a-z]{2}\K(\d)/$1+1/gie;
print;
}
__DATA__
Format="%05dA1"
StartValue="2"
Format="%05dB1"
StartValue="2"
Format="%05dC1"
StartValue="2"
产量
Format="%05dA2"
StartValue="2"
Format="%05dB2"
StartValue="2"
Format="%05dC2"
StartValue="2"
如果您坚持使用Perl的旧版本,则只需捕获第一部分,然后使用
s/(%05[a-z]{2})(\d)/$1.($2+1)/gie;
将最后一个数字加1
perl -pe 's| (%.+) (\d)|$1. ($2+1)|xe' input_file
使用4参数substr
。 例如, 05d
$StartValue
的内容替换05d
和2个单词字符05d
一位数字,可以执行以下操作:
$Format =~ m/05d\w{2}\d/; substr( $Format, $-[0] + 5, 1, $StartValue );
对m//
的初始调用将@-
数组加载到匹配位置,并且substr
替换了适当的子字符串。
什么地方出了错?
您的正则表达式05d\\w{2}\\d{1}
匹配6个字符,因此它将不匹配05dA1
和co,您可能希望使用05d\\w\\d
或05\\w{2}\\d
( {1}
是不必要的)。
另外, s
的替换面也不是正则表达式,因此\\w{2}
表示转义序列\\w
(如果不存在此类序列,则为立即数w
),后跟用大括号括起来的立即数2
。
如果要在替换端重用捕获的字符串,则可以使用捕获组,例如$1
或其他特殊变量,例如$&
(注意:perlre提到使用$&
“可能会大大降低程序速度”)。
对于Perl v5.10及更高版本,您可以执行此操作
$main_course =~ s/05d\w\K\d/$name/g
\\K
是一个后置断言,这意味着与05d\\w
匹配的子字符串不包含在05d\\w
s
替换的字符串中 perl -pe 's/(Format.*[A-Z])(\d+)/$1.($2+1)/ge;' your_file
测试:
> cat temp
Format="%05dA1"
StartValue="2"
Format="%05dB1"
StartValue="2"
Format="%05dC1"
StartValue="2"
> perl -pe 's/(Format.*[A-Z])(\d+)/$1.($2+1)/ge;' temp
Format="%05dA2"
StartValue="2"
Format="%05dB2"
StartValue="2"
Format="%05dC2"
StartValue="2"
>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.