Python正则\w匹配中文的问题

在py3的时候,我想匹配字符串中的字母,直接用\w,匹配字符数字和下划线
def reg():
    pattern = re.compile(r'(\w+)')
    text = '*心机B_DI*梗塞I_DI*'
    # pattern = re.compile(r'([A-Z]_[A-Z]+)')
    res = pattern.findall(text)
    print(res)

['心机B_DI', '梗塞I_DI']

结果竟然连中文都被匹配出来了,查了一下,

\w匹配的是能组成单词的字符,在python3 中re默认支持的是unicode字符集,当然也支持汉字。只要加入re.A就可以解决这样问题,当然用注释掉的部分是安全可以匹配出来的。
def reg():
    pattern = re.compile(r'(\w+)', re.A)
    text = '*心机B_DI*梗塞I_DI*'
    # pattern = re.compile(r'([A-Z]_[A-Z]+)')
    res = pattern.findall(text)
    print(res)

['B_DI', 'I_DI']

py2中不会有这样的问题

>>> import re
>>> pattern = re.compile(r'(\w+)')
>>> text = '*心机B_DI*梗塞I_DI*'
>>> res = pattern.findall(text)
>>> print res
['B_DI', 'I_DI']

猜你喜欢

转载自blog.csdn.net/suzimuyu99/article/details/80924402