Python正则表达式获取URL

时间:2014-06-11 20:37:57

标签: python regex string parsing

我想从长字符串中获取一个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

4 个答案:

答案 0 :(得分: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'
>>>

答案 1 :(得分:0)

WWW\.(.+)\.[A-Z]{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)

答案 2 :(得分:0)

我刚才为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';

答案 3 :(得分: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 
相关问题