2024-10-03 11:16:46 发布
网友
我有base64编码的字符串,但在结尾有时会出现一些尾随垃圾,总是以没有有效的base64字符开头。如何提取从开始到第一个无base64有效字符的有效字符串?在
例如:
data = "(there is more valid content)gw3AQEFGh8NFgoqDwYsAQALDVFPVltYVkNGXldCRFUbNRk=----------:jhawrewre:--\r\n"
有效部分将没有"----------:jhawrewre:--\r\n"
"----------:jhawrewre:--\r\n"
可以使用正则表达式删除无效部分:
import re invalid_tail = re.compile(r'[^a-zA-Z0-9+/=\n\r].*$') def remove_tail(base64_value): return invalid_tail.sub('', base64_value)
[^a-zA-Z0-9+/=\n\r]匹配任何非有效Base64字符的字符,加上尾随的=填充、换行符和回车符(在编码值中允许换行)。在
[^a-zA-Z0-9+/=\n\r]
=
演示:
或者,使用样品的可解码部分:
>>> data = "3AQEFGh8NFgoqDwYsAQALDVFPVltYVkNGXldCRFUbNRk= :jhawrewre: \r\n" >>> remove_tail(data).decode('base64') '\xdc\x04\x04\x14h|4X(\xa8<\x18\xb0\x04\x00,5E=YmaY\r\x19y]\t\x11Tl\xd4d'
此解决方案在速度上轻松击败itertools.takewhile()选项:
itertools.takewhile()
>>> import timeit >>> text = "gw3AQEFGh8NFgoqDwYsAQALDVFPVltYVkNGXldCRFUbNRk= :jhawrewre: \r\n" >>> timeit.timeit('test(text)', 'from __main__ import with_takewhile as test, text') 11.785380125045776 >>> timeit.timeit('test(text)', 'from __main__ import with_re as test, text') 1.480334997177124
对于这个简单的示例,使用正则表达式的速度几乎快10倍;对于较长的文本,结果将更快。在
您可以使用^{}:
Make an iterator that returns elements from the iterable as long as the predicate is true.
predicate
>>> from itertools import takewhile >>> from string import letters,digits >>> valid_chars = letters + digits + '+/=' >>> text = "gw3AQEFGh8NFgoqDwYsAQALDVFPVltYVkNGXldCRFUbNRk= :jhawrewre: \r\n" >>> "".join(takewhile(lambda x:x in valid_chars, text)) 'gw3AQEFGh8NFgoqDwYsAQALDVFPVltYVkNGXldCRFUbNRk='
可以使用正则表达式删除无效部分:
[^a-zA-Z0-9+/=\n\r]
匹配任何非有效Base64字符的字符,加上尾随的=
填充、换行符和回车符(在编码值中允许换行)。在演示:
^{pr2}$或者,使用样品的可解码部分:
此解决方案在速度上轻松击败
itertools.takewhile()
选项:对于这个简单的示例,使用正则表达式的速度几乎快10倍;对于较长的文本,结果将更快。在
您可以使用^{} :
演示:
相关问题 更多 >
编程相关推荐