繁体   English   中英

Python正则表达式获取URL

[英]Python regular expression to get URL

我试图从长字符串中获取URL,但不确定如何编写正则表达式;

$ 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

但是它们全都在(-)和(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'
>>>

WWW\\.(.+)\\.[AZ]{2,3}

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)

不久前,我为一个PHP项目编写了以下正则表达式,它基于专用RFC,因此它将覆盖任何有效的URL。 我记得我也对其进行了广泛的测试,因此它应该可靠。

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';

您也可以使用此正则表达式。

>>> 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 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM