我有一个 SQL 转储文件,其中包含带有 html 链接的文本,例如:
<a href="http://blahblah.org/kb/getattachment.php?data=NHxUb3Bjb25fZGF0YS1kb3dubG9hZF9ob3d0by5wZGY=">attached file</a>
我想查找、解码并替换每个链接中文本的 Base64 部分。
我一直在尝试使用带有正则表达式和 base64 的 Python 来完成这项工作。但是,我的正则表达式技能无法胜任这项任务。
我需要选择以
开头的任何字符串'getattachement.php?data='
并以
结尾'"'
然后我需要使用 base64.b64decode() 解码 'data=' 和 '"' 之间的部分
结果应该类似于:
<a href="http://blahblah.org/kb/4/Topcon_data-download_howto.pdf">attached file</a>
我认为解决方案如下:
import re
import base64
with open('phpkb_articles.sql') as f:
for line in f:
re.sub(some_regex_expression_here, some_function_here_to_decode_base64)
有什么想法吗?
编辑:回答任何感兴趣的人。
import re
import base64
import sys
def decode_base64(s):
"""
Method to decode base64 into ascii
"""
# fix escaped equal signs in some base64 strings
base64_string = re.sub('%3D', '=', s.group(1))
decodedString = base64.b64decode(base64_string)
# substitute '|' for '/'
decodedString = re.sub('\|', '/', decodedString)
# escape the spaces in file names
decodedString = re.sub(' ', '%20', decodedString)
# print 'assets/' + decodedString + '"' # Print for debug
return 'assets/' + decodedString + '"'
count = 0
pattern = r'getattachment.php\?data=([^&]+?)"'
# Open the file and read line by line
with open('phpkb_articles.sql') as f:
for line in f:
try:
# globally substitute in new file path
edited_line = re.sub(pattern, decode_base64, line)
# output the edited line to standard out
sys.stdout.write(edited_line)
except TypeError:
# output unedited line if decoding fails to prevent corruption
sys.stdout.write(line)
# print line
count += 1
最佳答案
你已经有了它,你只需要小块:
pattern: r'data=([^&]+?)"'
将匹配 data=
之后和 "
< 之前的任何内容/p>
>>> pat = r'data=([^&]+?)"'
>>> line = '<a href="http://blahblah.org/kb/getattachment.php?data=NHxUb3Bjb25fZGF0YS1kb3dubG9hZF9ob3d0by5wZGY=">attached file</a>'
>>> decodeString = re.search(pat,line).group(1) #because the b64 string is capture by grouping, we only want group(1)
>>> decodeString
'NHxUb3Bjb25fZGF0YS1kb3dubG9hZF9ob3d0by5wZGY='
然后您可以使用 str.replace()
方法以及 base64.b64decode()
方法来完成剩下的工作。我不想只为您编写代码,但这应该可以让您很好地了解该去哪里。
关于python - 查找、解码并替换文本文件中的所有 Base64 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33487243/