开发者

Gruber’s URL Regular Expression in Python

开发者 https://www.devze.com 2022-12-15 08:41 出处:网络
How do I rewrite this new way to recognise addresses to work in Python? \\b(([\\w-]+://?|www[.])[^\\s()<>]+(开发者_高级运维?:\\([\\w\\d]+\\)|([^[:punct:]\\s]|/)))The original source for that st

How do I rewrite this new way to recognise addresses to work in Python?

\b(([\w-]+://?|www[.])[^\s()<>]+(开发者_高级运维?:\([\w\d]+\)|([^[:punct:]\s]|/)))


The original source for that states "This pattern should work in most modern regex implementations" and specifically Perl. Python's regex implementation is modern and similar to Perl's but is missing the [:punct:] character class. You can easily build that using this:

>>> import string, re
>>> pat = r'\b(([\w-]+://?|www[.])[^\s()<>]+(?:\([\w\d]+\)|([^%s\s]|/)))'
>>> pat = pat % re.sub(r'([-\\\]])', r'\\\1', string.punctuation)

The re.sub() call escapes certain characters inside the character set as required.

Edit: Using re.escape() works just as well, since it just sticks a backslash in front of everything. That felt crude to me at first, but certainly works fine for this case.

>>> pat = pat % re.escape(string.punctuation)


I don't think python have this expression

[:punct:]

Wikipedia says [:punct:] is same to

[-!\"#$%&\'()*+,./:;<=>?@\\[\\\\]^_`{|}~]


Python doesn't have the POSIX bracket expressions.

The [:punct:] bracket expression is equivalent in ASCII to

[!"#$%&'()*+,\-./:;<=>?@[\\\]^_`{|}~] 
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号