【问题标题】:Python, github search regular expression [duplicate]Python、github搜索正则表达式[重复]
【发布时间】:2019-11-23 14:34:41
【问题描述】:

我在 Python 中准备了一个搜索 github 网页的正则表达式:

github = re.findall(
    "https?:\/\/(?:www\.)?github\.com\/[A-Za-z0-9_-]+\/?", 
text)

但现在它会搜索以 https 开头的链接。如何修改它,因此正则表达式将搜索以 https 或仅以 www 开头的字符串?

现在我的正则表达式会找到这个:

https://github.com/helloman

还有这个:

https://www.github.com/helloman

但不是这个:

www.github.com/helloman

如何更改以接受所有三个选项?

【问题讨论】:

  • 这个问题对我来说不是很清楚。你能发布一些示例网址吗?
  • 已编辑,希望现在更好
  • 我用所有树示例测试了你的正则表达式,它已经做了你想要的。看不出有什么问题。你能澄清一下吗?
  • 我很确定它不适用于像www.github.com/XXX这样的地址
  • 因此,您想查找以www. https?://(?:www\.)? 开头的URL。您可以使用 OR 语法来做到这一点:(thing)|(another thing)。或者使用this 收集所有URL,然后使用URL 解析器(我认为是urllib 提供的)来检查域

标签: python regex


【解决方案1】:

这样就可以了:

(?:https?://)?(?:www[.])?github[.]com/[\w-]+/?

这是一个概念证明:

Python 3.7.5 (default, Oct 17 2019, 12:16:48) 
[GCC 9.2.1 20190827 (Red Hat 9.2.1-1)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import re
>>> github=re.compile('(?:https?://)?(?:www[.])?github[.]com/[\w-]+/?')
>>> github.findall('www.github.com/accdias/dotfiles.git')
['www.github.com/accdias/']
>>> github.findall('github.com/accdias/dotfiles.git')
['github.com/accdias/']
>>> github.findall('https://github.com/accdias/dotfiles.git')
['https://github.com/accdias/']
>>> github.findall('http://github.com/accdias/dotfiles.git')
['http://github.com/accdias/']
>>> github.findall('http://www.github.com/accdias/dotfiles.git')
['http://www.github.com/accdias/']
>>> github.findall('https://www.github.com/accdias/dotfiles.git')
['https://www.github.com/accdias/']
>>> 

希望对你有帮助。

【讨论】:

  • github.findall('www.github.com/accdias/dotfiles.git') == [],但 OP 想要一个 接受此 URL 的正则表达式
  • 哦!现在我明白了。感谢您的澄清。我的印象是 OP 想要排除那些没有协议的人。
  • 恕我直言 ///{2} 更清晰,你错过了连字符,OP 说 [A-Za-z0-9_-]+[\w-]+,而不是单独的 \w+
  • @Toto,确实如此。我会更新答案。感谢您提出这个问题。
【解决方案2】:

您只缺少几个括号。

https://regex101.com/r/NEuD5f/2

(https:\/\/)?(www\.)?github\.com\/[A-Za-z0-9_-]+\/?

附:

它现在也将匹配github.com/xxx。我不确定那是你想要的。

【讨论】:

  • 现在我从我使用的文本中得到[('', 'www.')]
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-08-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-11-14
  • 2016-04-21
  • 2019-08-12
相关资源
最近更新 更多