【问题标题】:re.findall -> RegEx in Pythonre.findall -> Python 中的正则表达式
【发布时间】:2021-09-30 10:38:48
【问题描述】:
import regex
frase = "text https://www.gamivo.com/product/sea-of-thieves-pc-xbox-one other text https://www.gamivo.com/product/fifa-21-origin-eng-pl-cz-tr"
x = regex.findall(r"/((http[s]?:\/\/)?(www\.)?(gamivo\.com\S*){1})", frase) 
print(x)

结果:

[('www.gamivo.com/product/sea-of-thieves-pc-xbox-one', '', 'www.', 'gamivo.com/product/sea-of-thieves-pc-xbox-one'), ('www.gamivo.com/product/fifa-21-origin-eng-pl-cz-tr', '', 'www.', 'gamivo.com/product/fifa-21-origin-eng-pl-cz-tr')]

我想要类似的东西:

[('https://www.gamivo.com/product/sea-of-thieves-pc-xbox-one', 'https://gamivo.com/product/fifa-21-origin-eng-pl-cz-tr')]

我该怎么做?

【问题讨论】:

  • 删除第一个 / 并使用非捕获组。 r'(?:https?://)?(?:www\.)?gamivo\.com\S*',见this demo
  • 你真的需要正则表达式吗?在空格上拆分并在结果数组中使用带有 https 的空格
  • @leoOrion 是的,它适用于需要正则表达式的更大项目。所以在最终项目中,我将替换为 str.replace() 以使用短链接

标签: python regex python-regex


【解决方案1】:

你需要

  1. 删除使https:///http://的匹配无效的初始/字符,因为/出现在http之后
  2. 删除不必要的捕获组和{1} 量词
  3. 将可选捕获组转换为非捕获组。

this Python demo:

import re
frase = "text https://www.gamivo.com/product/sea-of-thieves-pc-xbox-one other text https://www.gamivo.com/product/fifa-21-origin-eng-pl-cz-tr"
print( re.findall(r"(?:https?://)?(?:www\.)?gamivo\.com\S*", frase) )
# => ['https://www.gamivo.com/product/sea-of-thieves-pc-xbox-one', 'https://www.gamivo.com/product/fifa-21-origin-eng-pl-cz-tr']

也请参阅regex demo。另请参阅相关的re.findall behaves weird 帖子。

【讨论】:

    【解决方案2】:

    试试这个,它将把字符串从 https 开始到单个空格或换行符。

    import re
    frase = "text https://www.gamivo.com/product/sea-of-thieves-pc-xbox-one other text https://www.gamivo.com/product/fifa-21-origin-eng-pl-cz-tr"
    x = re.findall('(https?://(?:[^\s]*))', frase)
    print(x)
    # ['https://www.gamivo.com/product/sea-of-thieves-pc-xbox-one', 'https://www.gamivo.com/product/fifa-21-origin-eng-pl-cz-tr']
    

    【讨论】:

      猜你喜欢
      • 2023-03-25
      • 2012-02-18
      • 2012-06-19
      • 2020-05-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多