Python:将正则表达式替换为字符串以用作正则表达式

时间:2013-08-28 13:07:52

标签: python regex string

我有一个字符串:

s = 'This is a number -N-'

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

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

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

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

但是,我无法用正则表达式替换不能超越斜杠的正则表达式:

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

请告诉我这里我做错了什么。谢谢!

2 个答案:

答案 0 :(得分:4)

您的字符串只包含单个\,请使用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

答案 1 :(得分:-1)

为什么不使用替换?

 s.replace('-N-','(\d+)')