【问题标题】:How to choose first match from Alternation regex?如何从交替正则表达式中选择第一个匹配?
【发布时间】:2020-08-28 15:37:45
【问题描述】:

我正在尝试从推文中提取以“https:...”开头的 URL 之前的所有文本。

示例推文:

“由于冠状病毒,这种传统发型重新流行起来,肯尼亚人正在使用它来提高认识 https://...(视频来自 @QuickTake)”

在此示例中,我想删除“https://...(视频来自 @QuickTake)”并从头开始获取文本。 但它也适用于推文中没有任何 URL 链接的推文。

我已经尝试过这个表达式,并在它带有 URL 时得到了两个匹配项:

/(.*)(?=\shttps.*)|(.*)

我怎样才能让它只从推文中检索文本。

提前致谢!

【问题讨论】:

  • 您可能希望删除 http、tweet = re.sub(r'\s*https.*', '', tweet)之后的所有内容
  • 完美,解决了!

标签: python regex tweepy tweets


【解决方案1】:

这可能过于简单化了,但一个简单的str.find 就可以解决问题:

>>> s = "This traditional hairdo is back in fashion thanks to the coronavirus, and Kenyans are using it to raise awareness https://... (Video via @QuickTake)"
>>> s[:s.find('https://')]
'This traditional hairdo is back in fashion thanks to the coronavirus, and Kenyans are using it to raise awareness '

你基本上只是索引推文直到你找到https://的第一个实例。

请注意,如果https:// 没有出现在推文中,这种方法将不起作用。当https:// 未找到时,s.find('https://') 将返回-1,这会打乱我们的索引。如果没有找到,只需将索引器(下面的link_index)设置为完整推文的长度:

>>> s = 'this is some tweet without a URL'
>>> link_index = s.find('https://')
>>> if link_index == -1:
...     link_index = len(s)
... 
>>> s[:link_index]
'this is some tweet without a URL'

【讨论】:

    【解决方案2】:

    您可以删除https 以及后面的所有内容,直到字符串结尾,使用

    tweet = re.sub(r'\s*https.*', '', tweet)
    

    详情:

    • \s* - 0+ 个空格
    • https - 一个字符串
    • .* - 字符串的其余部分(行)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-16
      • 1970-01-01
      • 2023-03-25
      • 1970-01-01
      • 2011-02-20
      相关资源
      最近更新 更多