我试图从一个长字符串中获取一个 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
最佳答案
BUT they will all be in between a (-) and the (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'
>>>
下面是 Regex 模式匹配内容的分割:
- # -
\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'
>>>
关于Python正则表达式获取URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24172145/