python正则匹配URL

正则匹配URL过程

  1. 获得http请求头的字符串列表
  2. 正则匹配列表的第二个元素
  3. 判断正则匹配结果

正则匹配url_demo

import re

def main():

	name = """
	GET / HTTP/1.1
	Host: 127.0.0.1:9999
	Connection: keep-alive
	Cache-Control: max-age=0
	Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0                                          .8
	Upgrade-Insecure-Requests: 1
	User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Geck                                          o) Chrome/50.0.2661.102 Safari/537.36
	Accept-Encoding: gzip, deflate, sdch
	Accept-Language: zh-CN,zh;q=0.8

	GET /favicon.ico HTTP/1.1
	Host: 127.0.0.1:9999
	Connection: keep-alive
	User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Geck                                          o) Chrome/50.0.2661.102 Safari/537.36
	Accept: */*
	Referer: http://127.0.0.1:9999/
	Accept-Encoding: gzip, deflate, sdch
	Accept-Language: zh-CN,zh;q=0.8

	"""
	# str.splitlines([keepends])
	# http://www.runoob.com/python3/python3-string-splitlines.html
	# keepends -- 在输出结果里是否去掉换行符('\r', '\r\n', \n'),默认为 False,不包含换行符,如果为 True,则保留换行符。

	# str1 = name.splitlines(True)
	# print("保留换行符结果:\n",str1)
	str2 = name.splitlines(False)
	# print("不保留换行符结果:\n",str2)
	url_name = re.match(r"[^/]+(/[^ ]*)",str2[1])
	if url_name:
		url_name = url_name.group(1)
		print("正则匹配到的结果是:",url_name)
	else:
		print("未成功匹配到数据")

	
if __name__ == '__main__':
	main()

运行结果

可以匹配到我们需要的url
python正则匹配URL_第1张图片

学习资料:

http://www.runoob.com/python3/python3-reg-expressions.html

你可能感兴趣的:(python)