2013-10-24 16 views
0

我發現了一個​​:正則表達式獲取網址失敗

(?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。有沒有人有一個想法如何得到這個工作?

回答

2

您的正則表達式字符串在;:'"末尾的雙引號結尾,所以這就是語法錯誤的原因。

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`!()\[\]{};:'\".,<>?«»「」‘’]))") 

注意,有;:'\"代替;:'"我很驚訝,誰寫p​​ythonregex.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', '', '', '', '')] 

不知道哪個角色是必要的,但肯定有一些奇怪的在那裏。

+0

聽起來很合理,但。但使用轉義版本會導致regex.findall(「http://foo.com/blah_blah」) – mkind

+0

的空結果列表好奇。現在看看它。 – foobarbecue

+0

我在輸入正則表達式規則時使用了原始字符串語法。編輯答案。 – foobarbecue