简体   繁体   English

在 perl 中搜索和替换特殊字符

[英]Search and replace a special character in perl

I want to search a character and replace it with a string.我想搜索一个字符并将其替换为字符串。 First, I search for ':' and replace it with 'to'.首先,我搜索“:”并将其替换为“to”。 Next I want to search '$' and replace it with 'END'.接下来我想搜索 '$' 并将其替换为 'END'。 This is the code that I've tried.这是我试过的代码。 In below code, it work for the first character but not the second character.在下面的代码中,它适用于第一个字符,但不适用于第二个字符。 I tried to use backslash to escape the special character '$' but it still did not work.我尝试使用反斜杠来转义特殊字符 '$' 但它仍然不起作用。 What else can I do?我还可以做些什么?

$string = "[9:8],
if ($string =~ /^.*:+/){
   $stringreplaced =~ s/:/to/g;
}

elsif ($string =~ /^.*\$+/){
   $stringreplaced =~ s/\$/END/g;
}

First of all, the code you posted doesn't even compile, yet you say it actually ran.首先,您发布的代码甚至无法编译,但您说它确实运行了。 Only post code that you've run.仅发布您已运行的代码。

Second, you're matching against the wrong string.其次,您正在匹配错误的字符串。 You're checking if $string contains the character, but you replace the characters in $stringreplaced .您正在检查$string包含该字符,但您替换了$stringreplaced的字符。 ALWAYS use use strict; use warnings;始终使用use strict; use warnings; use strict; use warnings; . . This would have caught this error.这将捕获此错误。

Third, you only check if the character ( : or $ ) is on the first line.第三,您只检查字符( :$ )是否在第一行。 This is because .这是因为. doesn't match line feeds without /s .不匹配没有/s换行符。

Finally, You only check if the string contains $ if it doesn't contain : because you used elsif .最后,您只检查字符串是否包含$如果它不包含:因为您使用了elsif

The following is all you need:以下是您所需要的:

$string =~ s/:/to/g;
$string =~ s/\$/END/g;

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

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