如何用正则表达式对数字累计达10位的字母数字串进行数字掩码?
累计数字达10位时的掩码处理方案
需求明确
忽略字符串中的非数字字符,统计累计数字数量:
- 当累计数字总数达到10的整数倍时,将对应组数的数字替换为
* - 不足10个的剩余数字保持原样
- 示例验证:
原字符串:abc23 56 dfg %#34567fhgh0 1234567890 abc345
输出结果:abc** ** dfg %#****fhgh ********** abc345
原字符串含23个数字,前20个(2组10个)被掩码,最后3个保留。
实现方案(结合正则与回调函数)
纯正则无法直接跟踪累计计数,需配合编程语言的回调函数实现状态记录,以Python为例:
import re def mask_matching_digits(match, count=[0]): count[0] += 1 total = sum(1 for c in match.string if c.isdigit()) return '*' if count[0] <= (total // 10) * 10 else match.group() input_str = "abc23 56 dfg %#34567fhgh0 1234567890 abc345" total_digits = sum(1 for c in input_str if c.isdigit()) output_str = re.sub(r'\d', mask_matching_digits, input_str) if total_digits >=10 else input_str print(output_str)
代码解释
- 先统计字符串中数字的总数量,若不足10则直接返回原字符串
- 用
re.sub匹配每个数字,通过回调函数中的计数器跟踪已匹配的数字位置 - 计数器值小于等于
(总数字数//10)*10时,将数字替换为*,剩余数字保留原样
简化场景:总数字量≥10则掩码所有数字
如果需求是只要总数字量达到10位,就掩码所有数字,可直接用带正向预查的正则:
import re input_str = "abc23 56 dfg %#34567fhgh0 1234567890 abc345" output_str = re.sub(r'(?=(?:\D*\d){10,})\d', '*', input_str) print(output_str)
正则说明
(?=(?:\D*\d){10,}):正向预查,确认从当前位置到字符串末尾,至少存在10个数字(忽略非数字字符)- 匹配所有满足条件的数字,替换为
*
内容的提问来源于stack exchange,提问作者rohit garg
相关产品推荐
相关产品推荐

