您的字符串仅包含 single \
,用于print
查看实际的字符串输出:
str
版本:
>>> print re.sub(r'-N-', r'(\d+)', 'This is a number -N-')
This is a number (\d+)
repr
版本:
>>> re.sub(r'-N-', r'(\d+)', 'This is a number -N-')
'This is a number (\\d+)'
>>> print repr(re.sub(r'-N-', r'(\d+)', 'This is a number -N-'))
'This is a number (\\d+)'
所以,你的正则表达式会正常工作:
>>> patt = re.compile(re.sub(r'-N-', r'(\d+)', 'This is a number -N-'))
>>> patt.match('This is a number 20').group(1)
'20'
>>> regex = re.sub(r'-N-', r'(\d+)', 'This is a number -N-')
>>> re.match(regex, 'This is a number 20').group(1)
'20'
欲了解更多信息:Difference between __str__ and __repr__ in Python