获取URL的Python正则表达式
我想从一串很长的文字中提取出一个网址,但我不太确定该怎么写正则表达式。
$ string = '192.00.00.00 - WWW.WEBSITE.COM GET /random/url/link'
我想用're.search'这个函数来提取出网址,比如只要“WWW.WEBSITE.COM”,而且中间不能有空格。我希望它看起来像这样:
$ get_site = re.search(regex).group()
$ print get_site
$ WWW.WEBSITE.COM
4 个回答
0
你也可以使用这个正则表达式。
>>> import re
>>> string = '192.00.00.00 - WWW.WEBSITE.COM GET /random/url/link'
>>> match = re.search(r'-\s+([^ ]+)\s+GET', string)
>>> match.group(1)
'WWW.WEBSITE.COM'
下面是对这个正则表达式的详细解释:
- # a literal -
\s+ # one or more spaces
([^ ]+) # Matches not of space character one or more times and () helps to store the captured characters into a group.
\s+ # one or more spaces
GET # All the above must followed the string GET
0
这个内容是一个正则表达式,用来匹配网址的一部分。具体来说,它的意思是:以“WWW.”开头,后面跟着一个或多个字符(可以是字母、数字或其他符号),然后是一个点(“.”),最后是两个到三个大写字母(比如“.COM”或“.NET”)。
WWW #WWW
\. #dot
(.+) #one or more arbitrary characters
\. #dot, again
[A-Z]{2,3} #two or three alphabetic uppercase characters (as there are .eu domain, for example)
0
我之前为一个PHP项目写了下面这个正则表达式,它是根据专门的RFC标准来的,所以可以匹配任何有效的网址。我记得我也进行了很多测试,所以这个正则表达式应该是可靠的。
const re_host = '(([a-z0-9-]+\.)+[a-z]+|([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])(\.([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])){3})';
const re_port = '(:[0-9]+)?';
const re_path = '([a-z0-9-\._\~\(\)]|%[0-9a-f]{2})+';
const re_query = '(\?(([a-z0-9-\._\~!\$&\'\(\)\*\+,;=:@/\?]|%[0-9a-f]{2})*)?)?';
const re_frag = '(#(([a-z0-9-\._\~!\$&\'\(\)\*\+,;=:@/\?]|%[0-9a-f]{2})*)?)?';
const re_localpart = '[a-z0-9!#\$%&\'*\+-/=\?\^_`{|}\~\.]+';
const re_GraphicFileExts = '\.(png|gif|jpg|jpeg)';
$this->re_href = '~^'.'('.'https?://'.self::re_host.self::re_port.'|)'.'((/'.self::re_path.')*|/?)'.'/?'.self::re_query.self::re_frag.'$~i';
7
但是它们都会在一个负号(-)和一个GET之间。
这就是你需要的所有信息:
>>> import re
>>> string = '192.00.00.00 - WWW.WEBSITE.COM GET /random/url/link'
>>> re.search('-\s+(.+?)\s+GET', string).group(1)
'WWW.WEBSITE.COM'
>>>
下面是对这个正则表达式模式匹配内容的详细解释:
- # -
\s+ # One or more spaces
(.+?) # A capture group for one or more characters
\s+ # One or more spaces
GET # GET
还要注意,.group(1)
获取的是由 (.+?)
捕获的文本。而 .group()
则会返回整个匹配的内容:
>>> re.search('-\s+(.+?)\s+GET', string).group()
'- WWW.WEBSITE.COM GET'
>>>