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

如何获取单个Unicode字符的全部十六进制编码?(Python正则场景)

获取字符的所有十六进制编码及正则匹配建议

针对你要匹配à这类特殊字符的需求,以下是获取其所有可能十六进制表示的方法,以及更高效的正则匹配方案:

1. 获取字符的Unicode等价表示(含预组合/分解形式)

很多字符在Unicode中有预组合和分解两种等价形式,比如à:

  • 预组合形式:U+00E0(单个字符)
  • 分解形式:U+0061(a) + U+0300(重音符̀)

用Python的unicodedata模块可以获取所有归一化形式,进而得到对应的十六进制:

import unicodedata

char = 'à'
# 四种Unicode归一化形式:NFC(预组合), NFD(分解), NFKC, NFKD
normalizations = ['NFC', 'NFD', 'NFKC', 'NFKD']
for norm in normalizations:
    normalized = unicodedata.normalize(norm, char)
    # 转成每个字符的十六进制表示
    hex_repr = ''.join([f'\\x{ord(c):02x}' for c in normalized])
    print(f'{norm}: {normalized} -> {hex_repr}')

运行后会输出:

NFC: à -> \xe0
NFD: à -> \x61\xcc\x80
NFKC: à -> \xe0
NFKD: à -> \x61\xcc\x80

(注:你之前写的\x61\x300是错误的,U+0300的UTF-8编码是\xcc\x80,不是\x300)

2. 获取不同编码标准下的十六进制

同一个字符在不同编码(UTF-8、UTF-16、ISO-8859-1等)下的十六进制不同,用Python的encode方法可以直接获取:

char = 'à'
encodings = ['utf-8', 'iso-8859-1', 'utf-16le', 'utf-16be']
for enc in encodings:
    try:
        hex_str = char.encode(enc).hex()
        # 转成正则风格的\x格式
        regex_hex = ''.join([f'\\x{hex_str[i:i+2]}' for i in range(0, len(hex_str), 2)])
        print(f'{enc}: {regex_hex}')
    except UnicodeEncodeError:
        print(f'{enc}: 无法编码该字符')

运行输出:

utf-8: \xe0
iso-8859-1: \xe0
utf-16le: \xe0\x00
utf-16be: \x00\xe0

3. 正则匹配的最佳实践

手动枚举所有十六进制编码容易遗漏,更可靠的方式是先归一化文本,再直接匹配字符:

import re
import unicodedata

def match_char(text, target_char):
    # 把文本和目标字符都归一化到NFC(预组合形式)
    normalized_text = unicodedata.normalize('NFC', text)
    normalized_target = unicodedata.normalize('NFC', target_char)
    # 直接匹配归一化后的字符
    return re.findall(normalized_target, normalized_text)

# 测试:包含分解形式的文本
test_text = 'a\xcc\x80 bc à'
print(match_char(test_text, 'à'))  # 输出: ['à', 'à']

如果必须用正则的十六进制写法,也可以基于归一化后的结果构建模式,比如:

target = unicodedata.normalize('NFD', 'à')
pattern = '|'.join([f'\\x{ord(c):02x}' for c in target]) + '|' + unicodedata.normalize('NFC', 'à').encode('utf-8').hex().replace('', '\\x')[2:]
# pattern结果: \x61\xcc\x80|\xe0

内容的提问来源于stack exchange,提问作者Dinh Quang Tuan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 08:40:27