【问题标题】:How to substitute arbitrary fixed strings in Perl如何在 Perl 中替换任意固定字符串
【发布时间】:2011-08-08 21:19:31
【问题描述】:

我想用 Perl 替换另一个字符串中的固定字符串。两个字符串都包含在变量中。

如果被替换的字符串不可能包含任何正则表达式元字符,我可以这样做:

my $text = 'The quick brown fox jumps over the lazy dog!';
my $search = 'lazy';
my $replace = 'drowsy';

$text =~ s/$search/$replace/;

唉,我希望它适用于任意 fixed 字符串。例如,这应该使 $text 保持不变:

my $text = 'The quick brown fox jumps over the lazy dog!';
my $search = 'dog.';
my $replace = 'donkey.';

$text =~ s/$search/$replace/;

相反,这会将dog! 替换为donkey.,因为点与感叹号匹配。

假设变量内容本身不是硬编码的,例如,它们可以来自文件或命令行,有没有办法引用或标记变量的内容,以便它们不会被解释为常规这种替换操作中的表达式?

或者有没有更好的方法来处理固定字符串?最好是仍然允许我使用类似正则表达式的功能,例如锚点或反向引用。

【问题讨论】:

    标签: perl string substitution


    【解决方案1】:

    通过quotemeta 运行您的$search:

    my $text = 'The quick brown fox jumps over the lazy dog!'; 
    my $search = quotemeta('dog.'); 
    my $replace = 'donkey.'; 
    
    $text =~ s/$search/$replace/;
    

    很遗憾,这将不允许您使用其他正则表达式功能。如果您有一组要逃避的精选功能,也许您可​​以通过第一个“清理”正则表达式或函数运行$search,例如:

    my $search = 'dog.';
    $search = clean($search);
    
    sub clean {
      my $str = shift;
      $str =~ s/\./\\\./g;
      return $str;
    }
    

    【讨论】:

    • +1 这正是我所需要的 - 不知道我是如何在perlfunc 中错过的。
    【解决方案2】:
    #Replace a string without using RegExp.
    sub str_replace {
        my $replace_this = shift;
        my $with_this  = shift; 
        my $string   = shift;
    
        my $length = length($string);
        my $target = length($replace_this);
    
        for(my $i=0; $i<$length - $target + 1; $i++) {
            if(substr($string,$i,$target) eq $replace_this) {
                $string = substr($string,0,$i) . $with_this . substr($string,$i+$target);
                return $string; #Comment this if you what a global replace
            }
        }
        return $string;
    }
    

    【讨论】:

    • 这就是他所说的,我现在(或曾经)只是链接到别人的代码。这不是我的意见。
    【解决方案3】:

    用\Q...\E 包裹您的搜索字符串,其中引用任何元字符。

    $text =~ s/\Q$search\E/$replace/;
    

    【讨论】:

    • +1 这会起作用,尽管我宁愿修复搜索字符串而不是替换运算符调用...
    • 这两种方法在不同的情况下都有用。如果我想实际修改搜索字符串,我会使用quotemeta()。如果我不想修改搜索字符串,我会使用\Q...\E。
    猜你喜欢
    • 2019-06-01
    • 2016-07-31
    • 1970-01-01
    • 1970-01-01
    • 2016-12-24
    • 1970-01-01
    • 2012-09-21
    • 2017-09-09
    • 2014-10-06
    相关资源
    最近更新 更多