在python中使用单词、表达式或模式拆分字符串



我正在使用web客户端GET请求解析信息。我有一个基于该数据的连接字符串,我想根据这个模式拆分字符串:"rn"。我基本上想要每个头信息位在它自己的行。我还想排除正文信息。

下面是我想要拆分的示例字符串的一部分:

'HTTP/1.1 400 Bad Request\r\nDate: Tue, 26 Oct 2021 11:26:46 GMT\r\nServer:

我有一个函数,我解析的信息,我已经尝试使用regex和分裂,但我不断得到错误(我是新的python和网络)。以下是我尝试过的一些例子(webinformation是要分割的字符串):

header = webinformation.splitlines()
for x in range(len(header)):
print(header[x])
下面是我尝试过的正则表达式的一个例子
print(re.split('\r\n', webinformation))

我怎样才能把每一位信息单独打印在一行上呢?我不确定这是否是转义字符的问题?

你可以用n代替空格而不使用regex:

a = 'HTTP/1.1 400 Bad Request\r\nDate: Tue, 26 Oct 2021 11:26:46 GMT\r\nServer:'
print(a.replace('\r\n', 'n'))

输出:

HTTP/1.1 400 Bad Request
Date: Tue, 26 Oct 2021 11:26:46 GMT
Server:

您有rn四字符行分隔符。

不需要正则表达式,因为它是固定文本。使用str.split:

text = 'HTTP/1.1 400 Bad Request\r\nDate: Tue, 26 Oct 2021 11:26:46 GMT\r\nServer:'
for line in text.split(r'rn'):
print(line)

查看Python演示。

输出:

HTTP/1.1 400 Bad Request
Date: Tue, 26 Oct 2021 11:26:46 GMT
Server:

就像这样:

➜  ~ ipython
Python 3.8.10 (default, Jun  2 2021, 10:49:15)
Type 'copyright', 'credits' or 'license' for more information
IPython 7.28.0 -- An enhanced Interactive Python. Type '?' for help.
In [1]: s = 'HTTP/1.1 400 Bad Request\r\nDate: Tue, 26 Oct 2021 11:26:46 GMT\r\nServer:'
In [2]: s.replace('\r\n', 'n').splitlines()
Out[2]: ['HTTP/1.1 400 Bad Request', 'Date: Tue, 26 Oct 2021 11:26:46 GMT', 'Server:']

最新更新