如何在一行中搜索和替换多个字符串 - Perl

时间:2018-01-24 16:27:17

标签: regex string perl replace

我想在一行(字符串)中搜索和替换多个字符串。

考虑我有三个变量

my $fruitone = "apple";
my $fruittwo = "orange";
my $fruitthree = "banana";

my string1 = "I have one ${fruitone} two ${fruittwo} and three ${fruitthree}";

我想将$fruitone替换为apple,依此类推。

我的最终结果应该是

I have one apple two orange and three banana.

我可以用string1 =~ /$\{(\w+)\}/$$1/;

替换一个

但我需要有关访问$2$3项目

的帮助

3 个答案:

答案 0 :(得分:1)

您的正则表达式只有一个捕获组,因此无法访问$2$3

如果你想匹配多个东西,你需要将g选项添加到最后,比如这个

$string1=~ s/\$\{(\w+)\}/$$1/g;

注意:这实际上不是编写代码的好方法,因为它允许任何变量替换为字符串。您应该考虑使用散列来存储值以限制可以替换的内容。

my %fruit=("fruitone" => "apple", "fruittwo"=>"orange","fruitthree" => "banana");
my $string1= 'I have one ${fruitone} two ${fruittwo} and three ${fruitthree}';

$string1 =~ s/\$\{(\w+)\}/$fruit{$1}/g;

答案 1 :(得分:0)

这似乎有效:

my($fruitone, $fruittwo, $fruitthree) = ("apple", "orange", "banana");
my $string= 'I have one ${fruitone} two ${fruittwo} and three ${fruitthree}';
$string =~ s/(\$\{\w+\})/eval$1/ge;

或者这个:

our($fruitone, $fruittwo, $fruitthree) = ("apple", "orange", "banana");
my $string= 'I have one ${fruitone} two ${fruittwo} and three ${fruitthree}';
$string =~ s/\$\{(\w+)\}/$$1/ge;

但是,如果可以,我建议您使用哈希值。

答案 2 :(得分:-1)

我认为你需要 String::Interpolate模块, 但我现在无法使用非核心模块进行测试,因为我使用的是Android平板电脑

我认为这应该有用

use strict;
use warnings 'all';

use String::Interpolate 'interpolate';

my $fruitone   = "apple";
my $fruittwo   = "orange";
my $fruitthree = "banana";

my $string = 'I have one ${fruitone} two ${fruittwo} and three ${fruitthree}';

print interpolate($string);