我有以下内容,并且尝试将其拆分为Key:值字典,其中的键是协议+版本,值是是否受支持。
['SSLv2 not offered (OK)',
'SSLv3 not offered (OK)',
'TLS 1 not offered',
'TLS 1.1 not offered',
'TLS 1.2 offered (OK)',
'TLS 1.3 not offered and downgraded to a weaker protocol',
'NPN/SPDY h2, http/1.1 (advertised)',
'ALPN/HTTP2 h2, http/1.1 (offered)']
我的问题是我无法找到一种巧妙的方式来拆分此内容,由于数据使用空格,因此无法按制表符进行拆分,而且由于某些协议也具有空格,因此无法按空格进行拆分。例:
re.split(r'\s+', entries.strip(), 1)
['SSLv2', 'not offered (OK)'], ['SSLv3', 'not offered (OK)'], ['TLS', '1 not offered'], ['TLS', '1.1 not offered'], ['TLS', '1.2 offered (OK)'], ['TLS', '1.3 not offered and downgraded to a weaker protocol'], ['NPN/SPDY', 'h2, http/1.1 (advertised)'], ['ALPN/HTTP2', 'h2, http/1.1 (offered)']]
如您所见,除了某些协议,它们都可以正常工作: ['ALPN/HTTP2', 'h2, http/1.1 (offered)']
原始数据如下所示:
SSLv2 not offered (OK)
SSLv3 not offered (OK)
TLS 1 not offered
TLS 1.1 not offered
TLS 1.2 offered (OK)
TLS 1.3 not offered and downgraded to a weaker protocol
NPN/SPDY h2, http/1.1 (advertised)
ALPN/HTTP2 h2, http/1.1 (offered)
我希望最终输出看起来像这样:
{
'SSLv2': 'not offered (OK)',
'SSLv3': 'not offered (OK)',
'TLS 1': 'not offered',
'TLS 1.1': 'not offered',
'TLS 1.2': 'offered (OK)',
'TLS 1.3': 'not offered and downgraded to a weaker protocol',
'NPN/SPDY': 'h2, http/1.1 (advertised)',
'ALPN/HTTP2': 'h2, http/1.1 (offered)'
}
您可以将以下正则表达式与一起使用re.findall
:
^(\S+(?:\s+\d+(?:\.\d+)*)?)\s+(.*)
请参阅regex演示。细节:
^
-字符串开始(\S+(?:\s+\d+(?:\.\d+)*)?)
-第1组:
\S+
-1个以上非空白字符(?:\s+\d+(?:\.\d+)*)?
-可选的非捕获组,匹配1+个空格,1 +个数字,然后出现0+个.
和1+个数字\s+
-1+空格(.*)
-第2组:其余的行/字符串。参见Python演示:
import re
entries = ['SSLv2 not offered (OK)', 'SSLv3 not offered (OK)', 'TLS 1 not offered', 'TLS 1.1 not offered', 'TLS 1.2 offered (OK)', 'TLS 1.3 not offered and downgraded to a weaker protocol', 'NPN/SPDY h2, http/1.1 (advertised)', 'ALPN/HTTP2 h2, http/1.1 (offered)']
for entry in entries:
print( dict(re.findall(r'^(\S+(?:\s+\d+(?:\.\d+)*)?)\s+(.*)', entry.strip())) )
输出:
{'SSLv2': 'not offered (OK)'}
{'SSLv3': 'not offered (OK)'}
{'TLS 1': 'not offered'}
{'TLS 1.1': 'not offered'}
{'TLS 1.2': 'offered (OK)'}
{'TLS 1.3': 'not offered and downgraded to a weaker protocol'}
{'NPN/SPDY': 'h2, http/1.1 (advertised)'}
{'ALPN/HTTP2': 'h2, http/1.1 (offered)'}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句