Python正则表达式获取URL

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

最佳答案

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/

相关文章:

python - 我可以在 python 3 中腌制然后在 python 2 中取消腌制吗?

json - 如何从 Scala 中的 jsonp 字符串中提取 json

c# - 字符串部分比较

python - 将一个 Twisted 工厂接收到的数据发送到第二个工厂

python - 一个类的值(value)是什么?

python - 如何在 Django 中将 select_related 与 GenericForeignKey 一起使用?

java - 使用正则表达式将相似的 xml 标签合并为单个标签

regex - 这些字符在 HTML、Postgres 和 Bash 中使用是否安全?

java - 正则表达式未正确匹配限制值

php - 我在字符串连接线解析错误: syntax error, unexpected T_CONSTANT_ENCAPSED_STRING in [closed]中遇到此错误