1.3.7.3 Unicode
在python3中,str对象使用完整的Unicode字符集,str的正则表达式处理会假设模式和输入文本都是Unicode.之前描述的转义码默认的也是按Unicode定义。这些假设意味着模式\w+对单词"French"和"Français"都能匹配。要向python2中的默认假设那样将转义码限制到ASCII字符集,编译模式或者调用模块级函数search()和match()时要使用ASCII码。
import re
text = u'Français österreich'
pattern = r'\w+'
ascii_pattern = re.compile(pattern,re.ASCII)
unicode_pattern = re.compile(pattern)
print('Text :',text)
print('Pattern :',pattern)
print('ASCII :',list(ascii_pattern.findall(text)))
print('Unicode :',list(unicode_pattern.findall(text)))
其他转义序列(\W,\b,\B,\d,\D,\s和\S)对ASCII文本也会采用不同的处理方式。re不再通过查询Unicode数据库来查找各个字符的属性,而是使用转义序列标识的字符集的ASCII定义。
运行结果:
Text : Français österreich
Pattern : \w+
ASCII : [‘Fran’, ‘ais’, ‘sterreich’]
Unicode : [‘Français’, ‘österreich’]