如何使用Perl正则表达式对字符串中的美元符号($)进行转义 [英] How to escape dollar sign ($) in a string using perl regex

查看:515
本文介绍了如何使用Perl正则表达式对字符串中的美元符号($)进行转义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用perl regex在给定的字符串中转义几个特殊字符.它对除美元符号以外的所有字符都适用.我尝试了以下方法:

I'm trying to escape several special characters in a given string using perl regex. It works fine for all characters except for the dollar sign. I tried the following:

my %special_characters;
$special_characters{"_"} = "\\_";
$special_characters{"$"} = "\\$";
$special_characters{"{"} = "\\{";
$special_characters{"}"} = "\\}";
$special_characters{"#"} = "\\#";
$special_characters{"%"} = "\\%";
$special_characters{"&"} = "\\&";

my $string = '$foobar';
foreach my $char (keys %special_characters) {
  $string =~ s/$char/$special_characters{$char}/g;
}
print $string;

推荐答案

尝试一下:

my %special_characters;
$special_characters{"_"} = "\\_";
$special_characters{"\\\$"} = "\\\$";
$special_characters{"{"} = "\\{";
$special_characters{"}"} = "\\}";
$special_characters{"#"} = "\\#";
$special_characters{"%"} = "\\%";
$special_characters{"&"} = "\\&";

看起来很奇怪,对吧?您的正则表达式需要如下所示:

Looks weird, right? Your regex needs to look as follows:

s/\$/\$/g

在正则表达式的第一部分,"$"需要转义,因为它是一个特殊的正则表达式字符,表示字符串的结尾.

In the first part of the regex, "$" needs to be escaped, because it's a special regex character denoting the end of the string.

正则表达式的第二部分被视为普通"字符串,其中"$"没有特殊含义.因此,反斜杠是真正的反斜杠,而在第一部分中,反斜杠用于转义美元符号.

The second part of the regex is considered as a "normal" string, where "$" doesn't have a special meaning. Therefore the backslash is a real backslash whereas in the first part it's used to escape the dollar sign.

此外,在变量定义中,您还需要转义反斜杠以及美元符号,因为它们在双引号字符串中都有特殊的含义.

Furthermore in the variable definition you need to escape the backslash as well as the dollar sign, because both of them have special meaning in double-quoted strings.

这篇关于如何使用Perl正则表达式对字符串中的美元符号($)进行转义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆