2

我有一个字符串:

s = 'This is a number -N-'

我想用-N-占位符代替正则表达式:

s = 'This is a number (\d+)'

所以我以后可以s用作正则表达式来匹配另一个字符串:

re.match(s, 'This is a number 2')

但是,我无法让 s 替换为不转义斜杠的正则表达式:

re.sub('-N-', r'(\d+)', 'This is a number -N-')
# returns 'This is a num (\\d+)'

请让我知道我在这里做错了什么。谢谢!

4

2 回答 2

4

您的字符串仅包含 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

于 2013-08-28T13:12:36.317 回答
-1

为什么不直接使用替换?

 s.replace('-N-','(\d+)')
于 2013-08-28T13:10:25.970 回答