【问题标题】:How can i search and replace multiple strings in a line - Perl如何在一行中搜索和替换多个字符串 - Perl
【发布时间】:2018-07-03 18:42:12
【问题描述】:

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

考虑我有三个变量

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

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

我想用apple替换$fruitone等等。

我的最终结果应该是这样的

I have one apple two orange and three banana.

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

但我在访问 $2$3 项目方面需要帮助

【问题讨论】:

  • my string 是语法错误(缺少 $)。此外,双引号会插入变量。
  • 我相信我没有理解这个问题。 :-( 当 Perl 会自动执行时,“手动”在字符串中插入变量的目的是什么?"I have one ${fruitone} …" 无论如何都会产生"I have one apple …"(使用" 时),不是吗?

标签: regex string perl replace


【解决方案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;

【讨论】:

  • 是的,谢谢你,我正在使用哈希来做到这一点,为简单起见,我这样写,你的回答很有帮助,谢谢!
  • @vijay 以后您应该首先使用实际代码提出您想要回答的问题,而不是碰巧导致您可以使用的答案的类似问题。
  • @Chris:您的回答很差,您无权责备 OP。你测试过你的代码吗?
  • @Borodin 它有效,但我没有使用 OP 的正则表达式对其进行测试,我现在看到其中有更多错别字:/
  • @Chris:一旦您将其发布为答案,它就是 您的 正则表达式。请不要再将你的错误归咎于他人。
【解决方案2】:

这似乎有效:

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;

但是,如果可以的话,我建议您对水果使用哈希。

【讨论】:

    【解决方案3】:

    我认为你需要 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);
    

    【讨论】:

      猜你喜欢
      • 2015-10-03
      • 2021-01-31
      • 2018-01-02
      • 1970-01-01
      • 1970-01-01
      • 2017-01-05
      • 2015-02-20
      • 2013-05-20
      • 2019-06-01
      相关资源
      最近更新 更多