再次使用Python正则表达式 - 匹配url

Tho*_*omK 5 python regex

我有这样的正则表达式:

 re.compile(r"((https?):((//)|(\\\\))+[\w\d:#@%/;$()~_?\+-=\\\.&]*)", re.MULTILINE|re.UNICODE)
Run Code Online (Sandbox Code Playgroud)

但这不包括hashbangs (#!).我需要改变什么才能让它发挥作用?我知道我可以添加!用#@%etc组合,但是会选择类似的东西

Check this out: http://example.com/something/!!!
Run Code Online (Sandbox Code Playgroud)

而我想避免这种情况.

kin*_*all 10

不要试图为匹配的URL创建自己的正则表达式,使用已解决此类问题的其他人,比如这个.

  • 虽然使用别人的代码没有任何问题,但编写自己的代码也没有错!:)我想如果每个人都会遵循这个建议_"不要试图让自己的<put_whatever_here>,使用别人的"_我们仍然会住在洞穴里!;) (11认同)
  • 链接中的正则表达式很糟糕:它试图列出 2011 年已知的顶级域名,但很快就过时了。 (3认同)
  • @mac - 如果每个人都必须重新发明一切,我们的进展会慢得多。使用别人完成的想法,然后通过改进它或添加新的东西来使它更好,要好得多。甚至牛顿也承认他是在其他人工作的基础上建立起来的。 (2认同)

Asa*_*sad 9

它可能会很长,但实际上我的效果很好。请试试这个 ((http|https)\:\/\/)?[a-zA-Z0-9\.\/\?\:@\-_=#]+\.([a-zA-Z]){2,6}([a-zA-Z0-9\.\&\/\?\:@\-_=#])*

它与下面的所有示例匹配

http://wwww.stackoverflow.com
abc.com
http://test.test-75.1474.stackoverflow.com/
stackoverflow.com/
stackoverflow.com
rfordyce@broadviewnet.com
http://www.example.com/etcetc
www.example.com/etcetc
example.com/etcetc
user:pass@example.com/etcetc
(www.itmag.com)
example.com/etcetc?query=aasd
example.com/etcetc?query=aasd&dest=asds
http://stackoverflow.com/questions/6427530/regular-expression-pattern-to-
match-url-with
www/Christina.V.Scott@gmail.com
line.lundvoll.nilsen@telemed.no.
s.hossain@unsw.edu.au
s.hossain@unsw.edu.au
Run Code Online (Sandbox Code Playgroud)

  • 我用我的示例文本“我打开了 https://google.com 和 http://speedtest.net 和 www.standford.edu”尝试了您的正则表达式,但没有得到正确的结果。这就是我得到 `[('https://', 'https', 'm', ''), ('http://', 'http', 't', ''), ('' , '', 'u', '')]` (2认同)

est*_*ani 6

这是一个常见问题。使用默认库。

对于 Python,请使用urlparse