You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python如何将Markdown内多模式匹配的人物标签替换为对应名称

解决方案

你当前的问题根源是正则仅匹配了标签内部的ID片段,只替换了ID部分未移除外层标签结构。调整思路如下:

  • 修改正则规则,直接匹配完整的![:Person](四位ID)标签,同时通过捕获组提取括号内的ID
  • 替换回调函数直接返回ID对应的姓名,即可直接把整段标签替换为姓名

修改后的完整可运行代码:

import re

names = {'1234': 'John Doe',
         '2345': 'Jane Smith',
         '3456': 'Marry Jones'
        }
        
message = '''![:Person](1234) ![:Person](2345) \nLorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in ![:Person](3456) voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.'''

def markdown(msg):
    # 匹配完整的Person标签,捕获4位ID
    person_pattern = re.compile(r'!\[:Person\]\((\d{4})\)')
    result = re.sub(person_pattern, replace_name, msg)
    return result
    
def replace_name(matchobj):
    # 取第一个捕获组的内容就是ID
    person_id = matchobj.group(1)
    if person_id in names:
        return names[person_id]
    # 若ID不在映射字典中,保留原标签避免内容丢失
    return matchobj.group(0)

print(markdown(message))

运行后输出结果完全符合预期,所有![:Person](四位ID)格式的标签都会被直接替换为对应的人员姓名,不会残留任何标签结构。

内容的提问来源于stack exchange,提问作者dreamzboy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 20:15:07