【问题标题】:regex for getting URLs fails获取 URL 的正则表达式失败
【发布时间】:2013-10-24 18:47:29
【问题描述】:

我找到了regex for getting urls from pages

(?i)\b((?:[a-z][\w-]+:(?:/{1,3}|[a-z0-9%])|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'".,<>?«»“”‘’]))

但是,我无法在 python 中应用它。即使声明包含此表达式的变量也会失败并显示“无效语法”消息:

Python 2.7.5 (default, Sep  6 2013, 09:55:21) 
[GCC 4.8.1 20130725 (prerelease)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> a = "(?i)\b((?:[a-z][\w-]+:(?:/{1,3}|[a-z0-9%])|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'".,<>?«»""'']))"
  File "<stdin>", line 1
    a = "(?i)\b((?:[a-z][\w-]+:(?:/{1,3}|[a-z0-9%])|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'".,<>?«»""'']))"
                                                                                                                                                                                                        ^
SyntaxError: invalid syntax

我试了一下here and it worked well。有谁知道如何让它工作?

【问题讨论】:

    标签: python html regex url


    【解决方案1】:

    您的正则表达式字符串以;:'" 末尾的双引号结尾,这就是语法错误的原因。

    pythonregex.com 自动添加一个 \ 来转义“,产生:

    regex = re.compile("(?i)\b((?:[a-z][\w-]+:(?:/{1,3}|[a-z0-9%])|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'\".,<>?«»“”‘’]))")
    

    请注意,它有 ;:'\" 而不是 ;:'" 。我很惊讶写 pythonregex.com 的人决定为你添加转义而不是让它给你一个语法错误。

    我发现在我的解释器上我需要使用 python r"raw string syntax" 来使它工作:

    In [31]: string="foo.com/blah_blah kuhiuh www.example.com"
    
    In [32]: In [29]: regex = re.compile(r"(?i)\b((?:[a-z][\w-]+:(?:/{1,3}|[a-z0-9%])|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'\".,<>?«»“”‘’]))")
    
    In [33]: regex.findall(string)
    Out[33]: [('foo.com/blah_blah', '', '', '', ''), ('www.example.com', '', '', '', '')]
    

    不确定是哪个字符需要 r,但肯定有一些奇怪的字符。

    【讨论】:

    • 听起来很合理。但是使用转义版本会导致 regex.findall("foo.com/blah_blah") 的结果列表为空
    • 很好奇。现在调查一下。
    • 我在输入正则表达式规则时使用原始字符串语法让它工作。编辑答案。
    猜你喜欢
    • 2013-08-25
    • 2018-04-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-09
    • 1970-01-01
    • 2014-09-04
    • 1970-01-01
    相关资源
    最近更新 更多