我有一个字符串:
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+)'
请告诉我这里我做错了什么。谢谢!
答案 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'
答案 1 :(得分:-1)
为什么不使用替换?
s.replace('-N-','(\d+)')