【问题标题】:How to use \1 backreference in python regex properly?如何在 python 正则表达式中正确使用 \1 反向引用?
【发布时间】:2014-06-02 02:45:29
【问题描述】:

我想选择[ ]括号内的内容

t="[abc/This is something] [testxyz] --include=*/ --include='some string/**' --exclude=*"
re.search('(\[[^\[\]]*\])\s*\1',t).groups()

为什么这没有返回?我也试过\\1,不行。当然(\[[^\[\]]*\])\s*(\[[^\[\]]*\]) 有效,但这不是应该使用\1 的地方吗?

预期结果是

['abc/This is something','testxyz']

【问题讨论】:

  • 您应该使用原始字符串,方法是在您的字符串前面加上r,如r'(\[[^\[\]]*\])\s*\1'。 StackOverflow 上有很多很多关于这个问题的问题。
  • 除了应该使用原始字符串这一事实之外,您可能还想使用re.findall()。不知道为什么在这里需要反向引用。
  • \1 是组 1 匹配内容的反向引用,但不引用子模式。
  • 反向引用的意思是“匹配被引用组匹配的确切文本”,而不是“匹配被引用组尝试匹配的相同类型的内容”。

标签: python regex string matching backreference


【解决方案1】:
import re
t="[abc/This is something] [testxyz] --include=*/ --include='some string/**' --exclude=*"
string = re.findall(r"\[(.*?)\]", t)
print string

#output ['abc/This is something', 'testxyz']

【讨论】:

  • 那么如何获取['abc/This is something', 'testxyz', ' --include=*/ --include='some string/**' --exclude=*"']呢?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-10-15
  • 1970-01-01
  • 2011-04-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-04-01
相关资源
最近更新 更多