Skip to main content
 首页 » 编程设计

Python re.sub 不返回匹配项

2025年05月04日14lori

在我的脑海中,如下:

>>> re.sub('([eo])', '_\1_', 'aeiou') 

应该返回:

'a_e_i_o_u' 

相反,它返回:

'a_\x01_i_\x01_u' 

我确定我脑抽筋了,但我终究无法弄清楚哪里出了问题。

请您参考如下方法:

\1 在 Python 字符串文字中生成 \x01。双斜杠,或使用原始字符串文字:

>>> import re 
>>> re.sub('([eo])', '_\1_', 'aeiou') 
'a_\x01_i_\x01_u' 
>>> re.sub('([eo])', '_\\1_', 'aeiou') 
'a_e_i_o_u' 
>>> re.sub('([eo])', r'_\1_', 'aeiou') 
'a_e_i_o_u' 

参见 The Backslash Plague在 Python 正则表达式 HOWTO 中:

As stated earlier, regular expressions use the backslash character ('\') to indicate special forms or to allow special characters to be used without invoking their special meaning. This conflicts with Python’s usage of the same character for the same purpose in string literals.