【问题标题】:Python: substituting a regular expression into a string to be used as a regular expressionPython:将正则表达式替换为要用作正则表达式的字符串
【发布时间】:2013-08-28 13:07:52
【问题描述】:

我有一个字符串:

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+)'

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

【问题讨论】:

  • 你不能只使用字符串方法吗? .format?

标签: python regex string


【解决方案1】:

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

【讨论】:

  • 我无法获取 re.sub() 的结果并将其作为正则表达式应用于后续的 re.match。你能验证它是否有效吗?
【解决方案2】:

为什么不直接使用替换?

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

【讨论】:

  • 根据我的测试也逃脱了斜线
猜你喜欢
  • 2022-11-07
  • 2015-11-30
  • 2019-04-17
  • 2017-02-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多