【问题标题】:Full expression for findallfindall 的完整表达式
【发布时间】:2013-03-06 14:36:01
【问题描述】:

我有一个正则表达式,它在某些文本中查找 url,例如:

my_urlfinder = re.compile(r'\shttp:\/\/(\S+.|)blah.com/users/(\d+)(\/|)')
text = "blah blah http://blah.com/users/123 blah blah http://blah.com/users/353"

for match in my_urlfinder.findall(text):
    print match  #prints an array with all the individual parts of the regex 

如何获取整个网址?目前 match 只是打印出匹配的部分(我需要其他的东西)......但我也想要完整的 url。

【问题讨论】:

  • 最简单的方法是添加一组额外的括号,将整个正则表达式括起来。然后你把它和零件一起搞定!

标签: python regex findall


【解决方案1】:

你应该让你的组不被捕获:

my_urlfinder = re.compile(r'\shttp:\/\/(?:\S+.|)blah.com/users/(?:\d+)(?:\/|)')

findall() 改变行为 当有捕获组时。使用组,它只会返回组,不捕获组,而是返回整个匹配的文本。

演示:

>>> text = "blah blah http://blah.com/users/123 blah blah http://blah.com/users/353"
>>> my_urlfinder = re.compile(r'\shttp:\/\/(?:\S+.|)blah.com/users/(?:\d+)(?:\/|)')
>>> for match in my_urlfinder.findall(text):
...     print match
... 
 http://blah.com/users/123
 http://blah.com/users/353

【讨论】:

    【解决方案2】:

    不使用任何捕获组的替代方法是在所有内容周围添加另一个:

    my_urlfinder = re.compile(r'\s(http:\/\/(\S+.|)blah.com/users/(\d+)(\/|))')
    

    这将允许您在保留整个结果的同时保留内部捕获组。

    对于演示文本,它将产生以下结果:

    ('http://blah.com/users/123', '', '123', '')
    ('http://blah.com/users/353', '', '353', '')
    

    作为旁注,请注意当前表达式需要在 URL 的 前面 有一个空格,因此如果文本以一个不匹配的开头。

    【讨论】:

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