您的当前位置:首页正文

Python中用正则表达式进行数据脱敏的几个示例

2024-11-30 来源:个人技术集锦

1. 对手机号码进行脱敏

import re

def desensitize_phone_number(phone_number):
    """
    对手机号码进行脱敏,保留前三位和后四位,中间四位用****代替
    """
    return re.sub(r'(\d{3})\d{4}(\d{4})', r'\1****\2', phone_number)

phone_number = "13812345678"
print(desensitize_phone_number(phone_number))

2. 对身份证号码进行脱敏

import re

def desensitize_id_card(id_card_number):
    """
    对身份证号码进行脱敏,保留前六位和后四位,中间部分用******代替
    """
    return re.sub(r'(\d{6})\d+(\d{4})', r'\1******\2', id_card_number)

id_card_number = "320123199012345678"
print(desensitize_id_card(id_card_number))

3. 对银行卡号进行脱敏

import re

def desensitize_bank_card(bank_card_number):
    """
    对银行卡号进行脱敏,保留前四位和后四位,中间部分用********代替
    """
    return re.sub(r'(\d{4})\d+(\d{4})', r'\1********\2', bank_card_number)

bank_card_number = "6222021234567890"
print(desensitize_bank_card(bank_card_number))

4. 对姓名进行脱敏(简单示例,只保留姓氏)

import re

def desensitize_name(name):
    """
    对姓名进行脱敏,只保留姓氏,名字部分用*代替
    """
    return re.sub(r'(\w+)\w*', r'\1*', name)

name = "张三"
print(desensitize_name(name))
显示全文