【发布时间】:2018-07-23 12:24:28
【问题描述】:
我有如下所示的数据示例,我想提取具有如下键/值模式的数据:
'Signature Algorithm: ecdsa-with-SHA256', 'Not Before: Jul 23 00:00:00 2018 GMT', 'Not After : Jul 19 00:00:00 2033 GMT, 'Public Key Algorithm: id-ecPublicKeyid', Public-Key: (256 bit)'
例子:
['Certificate:', 'Data:', 'Version: 3 (0x2)', 'Serial Number:', 'b9:d9:f5:38:f8:42:6a:f9', 'Signature Algorithm: ecdsa-with-SHA256', 'Issuer: C=US, ST=NC, L=Raleigh, O=Eaton Corporation, OU=Electrical Division, CN=PowerXpert-02-00-34-56-63-01', 'Validity', 'Not Before: Jul 23 00:00:00 2018 GMT', 'Not After : Jul 19 00:00:00 2033 GMT', 'Subject: C=US, ST=NC, L=Raleigh, O=Eaton Corporation, OU=Electrical Division, CN=PowerXpert-02-00-34-56-63-01', 'Subject Public Key Info:', 'Public Key Algorithm: id-ecPublicKey', 'Public-Key: (256 bit)', 'pub:', '04:bf:72:4b:01:8b:5c:46:98:96:a6:d6:06:7b:d8:', '73:50:2f:47:85:60:f0:38:25:79:3d:96:be:20:3b:', '3f:39:c8:58:62:e9:d7:b6:f8:3a:6b:24:50:e1:5c:', '78:ce:5e:28:f2:60:3a:b6:cc:43:0e:0b:2b:d6:03:', '51:76:21:a4:78', 'ASN1 OID: prime256v1', 'NIST CURVE: P-256', 'X509v3 extensions:', 'X509v3 Subject Key Identifier:', '6A:E0:28:A7:17:2B:65:01:FD:31:48:5C:68:24:94:4B:42:49:76:58', 'X509v3 Basic Constraints: critical', 'CA:TRUE', 'X509v3 Key Usage: critical', 'Digital Signature, Certificate Sign, CRL Sign', 'X509v3 Subject Alternative Name:', 'DNS:PXG900-56-63-01', 'Signature Algorithm: ecdsa-with-SHA256', '30:45:02:20:43:33:58:ce:ef:f7:fd:a8:60:21:15:a3:2b:35:', '8c:1f:13:a0:1e:77:05:6f:1a:bb:a0:b6:fe:f3:ea:7b:6d:31:', '02:21:00:cf:db:9a:d1:6b:88:ae:fb:d5:5c:5a:db:0a:a0:eb:', 'a9:c9:4a:52:d0:57:18:9c:58:1b:67:42:47:c5:ec:bf:b0', '', '']
使用下面的正则表达式但没有得到想要的结果
regex = re.compile(r'''
[\S]+: # a key (any word followed by a colon)
(?:
\s # then a space in between
(?!\S+:)\S+ # then a value (any word not followed by a colon)
)+ # match multiple values if present
''', re.VERBOSE)
matches = regex.findall(str(lines))
print(matches)
【问题讨论】:
-
lines这是一个列表吗? -
是的行是数据列表
-
想要的结果是什么?请格式化问题。
-
从显示的列表中,我想要数据的键/值模式,例如('签名算法:ecdsa-with-SHA256','Not Before: Jul 23 00:00:00 2018 GMT', '不是之后:格林威治标准时间 2033 年 7 月 19 日 00:00:00')
-
你可以把它变成一个字典并按照你想要的方式使用它:
dictionary = eval(re.sub(r"\s*'?([^,']+?)\s*:\s*([^,']+)[',]*",r"'\1':'\2',",a).join('{}'))其中a是你给的字符串。或者更确切地说,您可以将其拆分a.split(",")以生成下面给出的答案
标签: regex python-3.x python-2.7