【问题标题】:Python regex to match multiple timesPython正则表达式匹配多次
【发布时间】:2013-07-01 15:05:03
【问题描述】:

我正在尝试将模式与可能具有多个模式实例的字符串进行匹配。我需要单独的每个实例。 re.findall() 应该这样做,但我不知道我做错了什么。

pattern = re.compile('/review: (http://url.com/(\d+)\s?)+/', re.IGNORECASE)
match = pattern.findall('this is the message. review: http://url.com/123 http://url.com/456')

我需要 'http://url.com/123'、http://url.com/456 和两个数字 123 和 456 成为 match 列表的不同元素。

我也尝试过'/review: ((http://url.com/(\d+)\s?)+)/' 作为模式,但没有运气。

【问题讨论】:

  • 只需删除 review: 部分,因为第二个 http 在它之前不会有它。
  • 是的,但我需要那个,它是正则表达式的一部分。我不需要任何网址,只需要字符串'review:'之后的网址

标签: python regex multiple-matches


【解决方案1】:

使用这个。您需要将“review”放在捕获组之外才能达到预期的效果。

pattern = re.compile(r'(?:review: )?(http://url.com/(\d+))\s?', re.IGNORECASE)

这给出了输出

>>> match = pattern.findall('this is the message. review: http://url.com/123 http://url.com/456')
>>> match
[('http://url.com/123', '123'), ('http://url.com/456', '456')]

【讨论】:

  • 这工作,谢谢! (?:review ) 之后的 ? 也很关键,因为没有它它不会给我所有的匹配。 ;)
  • 别忘了import re
  • 没有findall怎么办? IE。对于需要匹配多个案例的案例,但这只是比赛的一部分?
【解决方案2】:

你在正则表达式中有额外的 /。在 python 中,模式应该只是一个字符串。例如而不是这个:

pattern = re.compile('/review: (http://url.com/(\d+)\s?)+/', re.IGNORECASE)

应该是:

pattern = re.compile('review: (http://url.com/(\d+)\s?)+', re.IGNORECASE)

通常在 python 中,您实际上会使用这样的“原始”字符串:

pattern = re.compile(r'review: (http://url.com/(\d+)\s?)+', re.IGNORECASE)

字符串前面的额外 r 使您不必进行大量反斜杠转义等操作。

【讨论】:

    【解决方案3】:

    使用两步方法:首先获取从“review:”到 EOL 的所有内容,然后对其进行标记。

    msg = 'this is the message. review: http://url.com/123 http://url.com/456'
    
    review_pattern = re.compile('.*review: (.*)$')
    urls = review_pattern.findall(msg)[0]
    
    url_pattern = re.compile("(http://url.com/(\d+))")
    url_pattern.findall(urls)
    

    【讨论】:

      猜你喜欢
      • 2020-10-10
      • 1970-01-01
      • 2021-12-11
      • 1970-01-01
      • 1970-01-01
      • 2015-09-19
      • 2023-03-16
      • 2014-03-06
      • 1970-01-01
      相关资源
      最近更新 更多