import re
from timeit import timeit
# Your example string
s = r"<000001|ABC=123|DEF=456|~GHI=TEST|JKL=O1234_ABC.pdf>"
# Using regex
a = re.findall(r'([^<=|>]+)=([^<|>]+)', s)
print("regex: ", dict(a))
# Using str.split()
b = map(lambda x: x.split('='), s.strip('<>').split('|')[1:])
print("split(): ", dict(b))
# Performance
t1 = timeit("re.findall(r'([^<=|>]+)=([^<|>]+)', s)", globals=globals(), number=1000000)
print("time for regex: {:3.2f} s".format(t1))
t2 = timeit("map(lambda x: x.split('='), s.strip('<>').split('|')[1:])", globals=globals(), number=1000000)
print("time for str.split(): {:3.2f} s".format(t2))
结果:
regex: {'ABC': '123', 'DEF': '456', '~GHI': 'TEST', 'JKL': 'O1234_ABC.pdf'}
split(): {'ABC': '123', 'DEF': '456', '~GHI': 'TEST', 'JKL': 'O1234_ABC.pdf'}
time for regex: 4.15 s
time for str.split(): 0.88 s
我知道,您明确要求通过regex提供解决方案,但请注意,在您的简单案例中没有必要使用regex
如果必须解析大量与示例类似的字符串,那么在避免regex和仅使用python内置的
split()
函数处理字符串方面可以获得更好的性能结果:
\w
只匹配字母、数字和下划线,不匹配~
或.
您应该使用一种模式来匹配除分隔符以外的任何内容:
<
在开头,|
在项目之间,=
在名称和值之间,以及>
在结尾相关问题 更多 >
编程相关推荐