简体   繁体   English

如何在 Perl 中替换任意固定字符串

[英]How to substitute arbitrary fixed strings in Perl

I want to replace a fixed string within another string using Perl.我想使用 Perl 替换另一个字符串中的固定字符串。 Both strings are contained in variables.两个字符串都包含在变量中。

If it was impossible for the replaced string to contain any regex meta-characters, I could do something like this:如果替换的字符串不可能包含任何正则表达式元字符,我可以这样做:

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

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

Alas, I want this to work for arbitrary fixed strings.唉,我希望这适用于任意固定字符串。 Eg, this should leave $text unchanged:例如,这应该保持$text不变:

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

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

Instead, this replaces dog!相反,这取代了dog! with donkey.donkey. , since the dot matches the exclamation mark. ,因为点与感叹号匹配。

Assuming that the variable contents themselves are not hardcoded, eg, they can come from a file or from the command line, is there a way to quote or otherwise markdown the contents of a variable so that they are not interpreted as a regular expression in such substitution operations?假设变量内容本身不是硬编码的,例如,它们可以来自文件或命令行,有没有办法引用或以其他方式标记变量的内容,以便它们不会被解释为这样的正则表达式替代操作?

Or is there a better way to handle fixed strings?或者有没有更好的方法来处理固定字符串? Preferably something that would still allow me to use regex-like features such as anchors or back-references.最好仍然允许我使用类似正则表达式的功能,例如锚点或反向引用。

Run your $search through quotemeta :通过quotemeta运行您的$search

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

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

This will unfortunately not allow you to use other regex features.不幸的是,这将不允许您使用其他正则表达式功能。 If you have a select set of features you want to escape out, perhaps you can just run your $search through a first "cleaning" regex or function, something like:如果你有一组你想要逃避的功能,也许你可以通过第一个“清理”正则表达式或函数来运行你的$search ,例如:

my $search = 'dog.';
$search = clean($search);

sub clean {
  my $str = shift;
  $str =~ s/\./\\\./g;
  return $str;
}

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

$text =~ s/\Q$search\E/$replace/;
#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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM