Skip to main content
 首页 » 编程设计

python之匹配文字字符串 '\$'

2025年05月04日24落叶

我正在尝试匹配文字字符串“\$”。我用反斜杠转义了“\”和“$”。为什么当我转义模式中的反斜杠时不起作用?但如果我使用一个点,它就会起作用。

import re 
 
print re.match('\$','\$') 
print re.match('\\\$','\$') 
print re.match('.\$','\$') 

输出:

None 
None 
<_sre.SRE_Match object at 0x7fb89cef7b90> 

有人可以解释一下内部发生的事情吗?

请您参考如下方法:

你应该使用 re.escape()为此功能:

escape(string)

Return string with all non-alphanumerics backslashed; this is useful if you want to match an arbitrary literal string that may have regular expression metacharacters in it.

例如:

import re 
val = re.escape('\$') # val = '\\\$' 
print re.match(val,'\$') 

输出:

<_sre.SRE_Match object; span=(0, 2), match='\\$'> 

这等同于 @TigerhawkT3 在他的 answer 中提到的内容.