【问题标题】:I need a regEx to match general URLs我需要一个正则表达式来匹配一般 URL
【发布时间】:2010-09-23 08:33:47
【问题描述】:

我需要使用任何协议(http、https、shttp、ftp、svn、mysql 和我不知道的东西)测试通用 URL。

我的第一关是这样的:

\w+://(\w+\.)+[\w+](/[\w]+)(\?[-A-Z0-9+&@#/%=~_|!:,.;]*)?

PCRE.NET 所以没什么好看的)

【问题讨论】:

  • 该表达式匹配太多(域名中不允许使用 _,IIRC,URL 可以在域名之后停止)并且不够匹配(可以在路径中找到 ~ 和任何 %hh 字符)。

标签: regex url string-matching


【解决方案1】:

将该正则表达式添加为 wiki 答案:

[\w+-]+://([a-zA-Z0-9]+\.)+[[a-zA-Z0-9]+](/[%\w]+)(\?[-A-Z0-9+&@#/%=~_|!:,.;]*)?

选项 2(重新 CMS)

^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?

但这对于任何理智的东西来说都是松懈的,如此修剪以使其更具限制性并与其他事物区分开来。

proto      ://  name      : pass      @  server    :port      /path     ? args
^([^:/?#]+)://(([^/?#@:]+(:[^/?#@:]+)?@)?[^/?#@:]+(:[0-9]+)?)(/[^?#]*)(\?([^#]*))?

【讨论】:

  • 另一种可能是'svn+ssh://'。我不认为 \w 会匹配 '+'。
【解决方案2】:

根据RFC2396

^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?

【讨论】:

  • 好的,所以 windows //server/dir/file 是一个 URL?让 FF/IE 中的 file:////server/dir/file 看起来更像集市
  • 这是一个非常危险的正则表达式。它实际上也捕获了 url 之前和之后的所有文本。它不适用于我的目的。在使用它之前,我肯定会检查一下。
【解决方案3】:

我是从一个稍微不同的方向来的。我想模拟 gchats 匹配something.co.uk 并链接它的能力。所以我使用了一个正则表达式,它查找.,没有后面的句点或两边的空格,然后抓住它周围的所有东西,直到它碰到空格。它确实匹配 URI 末尾的句点,但我稍后会取消它。因此,如果您希望误报而不是错过一些潜力,这可能是一个选择

url_re = re.compile(r"""
           [^\s]             # not whitespace
           [a-zA-Z0-9:/\-]+  # the protocol and domain name
           \.(?!\.)          # A literal '.' not followed by another
           [\w\-\./\?=&%~#]+ # country and path components
           [^\s]             # not whitespace""", re.VERBOSE) 

url_re.findall('http://thereisnothing.com/a/path adn some text www.google.com/?=query#%20 https://somewhere.com other-countries.co.nz. ellipsis... is also a great place to buy. But try text-hello.com ftp://something.com')

['http://thereisnothing.com/a/path',
 'www.google.com/?=query#%20',
 'https://somewhere.com',
 'other-countries.co.nz.',
 'text-hello.com',
 'ftp://something.com']

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-09-22
    • 1970-01-01
    • 2016-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多