【问题标题】:regex to find valide URL with or without www, including dot but excluding double dots正则表达式查找带或不带 www 的有效 URL,包括点但不包括双点
【发布时间】:2021-10-26 20:33:33
【问题描述】:

我正在尝试查找匹配包含或不包含“www”的 URL 的正则表达式,后跟可以包含点的有效字符串,但不能包含两个或多个连续点。为简单起见,我将问题仅限于具有子域和 .com 域的 URL。 例如:

www.aBC.com      #MATCH
abc.com          #MATCH
a_bc.de8f.com    #MATCH
a.com            #MATCH
abc              #NO MATCH
abc..com         #NO MATCH

我的正则表达式最接近的是\w+.[\w]+.com,但这与简单的“a.com”不匹配。我使用“\w”而不是“。”因为否则我不知道如何避免按顺序排列两个或多个点。

感谢任何帮助。

【问题讨论】:

    标签: python regex python-re


    【解决方案1】:

    使用

    (?:\w+\.)*\w+\.com
    

    regex proof

    解释

    -------------------------------------------------------------------------------
      (?:                      group, but do not capture (0 or more times
                               (matching the most amount possible)):
    --------------------------------------------------------------------------------
        \w+                      word characters (a-z, A-Z, 0-9, _) (1 or
                                 more times (matching the most amount
                                 possible))
    --------------------------------------------------------------------------------
        \.                       '.'
    --------------------------------------------------------------------------------
      )*                       end of grouping
    --------------------------------------------------------------------------------
      \w+                      word characters (a-z, A-Z, 0-9, _) (1 or
                               more times (matching the most amount
                               possible))
    --------------------------------------------------------------------------------
      \.                       '.'
    --------------------------------------------------------------------------------
      com                      'com'
    

    【讨论】:

    • 啊,我了解您的解决方案。该小组将保证包含“www”。如果存在,则二级域将包含在正则表达式的其余部分中。当没有“www,”时。由于星号,该小组仍然会抓住它。非常感谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-09-15
    • 1970-01-01
    • 2011-04-20
    • 2011-10-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多