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

如何使用Python正则替换将“五二式”编码转为带三位后缀的“四一式”编码

五二式编码转四一式编码Python实现

转换规则拆解

  • 原五二式编码结构:[姓氏全拼/前5位(姓氏≥5位时)] + [名字前2位] + [2位数字后缀],无补位规则
  • 目标四一式编码结构:[姓氏全拼/前4位(姓氏≥4位时)] + [名字前1位] + [3位数字后缀(不足补前导零)]

问题排查

你写的正则存在两个基础错误:

  1. 元字符书写错误:匹配字母数字的元字符是反斜杠开头的\w,不是正斜杠/w
  2. 分组逻辑不合理:没有利用正则贪婪匹配特性处理可变长度的姓氏部分,无法适配姓氏长度不足5的场景

可直接运行的实现方案

使用正则+替换回调函数实现,适配所有合法的五二式编码:

import re

# 编译匹配规则:贪婪匹配姓氏部分+固定匹配名字前2位+固定匹配2位数字后缀
code_pattern = re.compile(r'^([a-zA-Z]+)([a-zA-Z]{2})(\d{2})$')

def convert_52_to_41(code: str) -> str:
    match_res = code_pattern.fullmatch(code.strip())
    if not match_res:
        # 非法输入可根据业务需求自定义返回逻辑,这里默认返回原字符串
        return code
    surname_part, name_part, suffix_part = match_res.groups()
    # 按规则转换拼接
    return f"{surname_part[:4]}{name_part[:1]}{suffix_part.zfill(3)}"

# 测试示例
test_codes = [
    "adamsjo02",
    "allenje01",
    "alstoga01",
    "ariasge01",
    "aucoide01",
    "ayraujo01",
    "belkti01"
]
for code in test_codes:
    print(convert_52_to_41(code))

输出结果

和你给出的预期完全一致:

adamj002
allej001
alstg001
ariag001
aucod001
ayraj001
belkt001

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 17:27:02