【问题标题】:How to use {} in regex pattern with findall + Python如何通过 findall + Python 在正则表达式模式中使用 {}
【发布时间】:2017-05-03 11:00:40
【问题描述】:

我正在创建如下的正则表达式:

import re
asd = re.compile(r"(blah){2}")
mo = asd.search("blahblahblahblahblahblah ll2l 21HeHeHeHeHeHe lllo")
mo1 = asd.findall("blahblahblahblahblahblah")
print(mo.group())
print("findall output: ", mo1)

这将返回输出 废话 findall 输出:['blah', 'blah', 'blah']

-为什么 findall 输出匹配 'blah' 3 次,而其指定的 {2} 次仅在模式中?

如果我更改为 {4},则查找所有匹配项:

asd = re.compile(r"(blah){4}")
findall output:  ['blah']

-re.search 和 re.findall 如何处理 {m}?

非常感谢。

【问题讨论】:

  • blahblahblahblahblahblah。三场比赛。每个capturesblah.
  • 我想你也想告诉正则表达式引擎也只返回两个值,对吧?然后,您不需要限制量词:使用 re.findall 获取结果并使用它们的索引获取必要的项目。

标签: python regex findall


【解决方案1】:

如果你想捕捉(blah){2}(你有2个blah)你应该把它包装起来:

asd = re.compile(r"((?:blah){2})")

请注意,我确保不要抓住内部blah(使用?:

>>>asd = re.compile(r"((?:blah){2})")
>>>mo = asd.search("blahblahblahblahblahblah ll2l 21HeHeHeHeHeHe lllo")
>>>mo1 = asd.findall("blahblahblahblahblahblah")
>>>print(mo.group())
blahblah
>>>print("findall output: ", mo1)
findall output:  ['blahblah', 'blahblah', 'blahblah']

与您那里的{4} 完全相同。 regex 会找到它,但不会抓住它。如果你想抓住它,你应该把它包起来。

【讨论】:

    【解决方案2】:

    (blah){2} 捕获并耗尽字符串blahblah,但只返回blahblah 中的last blah。由于您的字符串中有三个blahblahs,它将输出['blah', 'blah', 'blah']

    (blah){4} 只能匹配一次,所以它会给你['blah']

    【讨论】:

      猜你喜欢
      • 2015-08-13
      • 2011-12-06
      • 1970-01-01
      • 1970-01-01
      • 2011-07-18
      • 1970-01-01
      • 2013-06-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多