Python回复sub用md5sum替换match

2024-04-24 11:48:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图解析这样一个字符串:

<@Something> there is some regular text <@something_else> and even more <@foo> <@bar> text

用它们的md5和替换所有的<@tokens>。你知道吗

用python可以吗回复sub?如何将@token传递给函数,并将函数的输出传递给re.sub?你知道吗

到目前为止,我尝试了最简单的方法:

import re

def fun(str):
    return str.replace('@', '!')

pattern = r'(<@\w+>)'
string = '<@AAAA> some text and more text <@BBBBB>'

print fun('<@AAAA>')
print string
print re.sub(pattern, fun(r'\1'), string)

没有成功。有趣的功能在外面也能正常工作回复sub(),但不在其中。你知道吗


Tags: and函数字符串textrestringmoresome
2条回答

使用hashlib库:

import hashlib, re

s = '<@Something> there is some regular text <@something_else> and even more <@foo> <@bar> text'
result = re.sub(r'<@[^>]+>', lambda m: hashlib.md5(m.group().encode()).hexdigest(), s)

print(result)

输出:

eb6eae14fb79abc1339b7096ae00a5e9 there is some regular text 16960eadb21d27a1b52e5c71a5ae7357 and even more 281dc7c0420f8e6ef66e58ecb979d087 31c0c5b91906d520a4dec601241833a6 text

https://docs.python.org/3/library/hashlib.html

是的,如the documentation所示,re.sub()的“replacement”参数可以是一个接受匹配对象并返回替换的函数。你知道吗

相关问题 更多 >