As the question says, I am trying to do a search replace using a variable and a capture group. That is, the replace string contains $1. I followed the answers here and here, but they did not working for me; $1 comes through in the replace. Can you help me spot my problem?
正如问题所说,我正在尝试使用变量和捕获组进行搜索替换。也就是说,替换字符串包含$ 1。我按照这里和这里的答案,但他们没有为我工作;更换中需要1美元。你能帮我发现我的问题吗?
I am reading my regular expressions from a file like so:
我正在从这样的文件中读取我的正则表达式:
while( my $line = <$file>) {
my @findRep = split(/:/, $line);
my $find = $findRep[0];
my $replace = '"$findRep[2]"'; # This contains the $1
$allTxt =~ s/$find/$replace/ee;
}
If I manually set my $replace = '"$1 stuff"'
the replace works as expected. I have played around with every single/double quoting and /e
combination I can think of.
如果我手动设置我的$ replace ='“$ 1 stuff”,则替换按预期工作。我已经玩过我能想到的每一个/双引号和/或组合。
2 个解决方案
#1
2
You're using single quotes so $findRep[2]
isn't interpolated. Try this instead:
你使用的是单引号,所以$ findRep [2]没有插值。试试这个:
my $replace = qq{"$findRep[2]"};
#2
1
Why regex replacement when you already have your values in @findRep
当你已经在@findRep中拥有值时,为什么要更换正则表达式
while( my $line = <$file>) {
my @findRep = split(/:/, $line);
$findRep[0] = $findRep[2];
my $allTxt = join(":", @findRep);
}
#1
2
You're using single quotes so $findRep[2]
isn't interpolated. Try this instead:
你使用的是单引号,所以$ findRep [2]没有插值。试试这个:
my $replace = qq{"$findRep[2]"};
#2
1
Why regex replacement when you already have your values in @findRep
当你已经在@findRep中拥有值时,为什么要更换正则表达式
while( my $line = <$file>) {
my @findRep = split(/:/, $line);
$findRep[0] = $findRep[2];
my $allTxt = join(":", @findRep);
}