[w]匹配项(字母数字或下划线)。
[W]匹配项(非(字母数字或下划线)),等同于(非字母数字和下划线)
您需要
[W_]删除所有非字母数字。
使用re.sub()时,如果通过匹配
[W_]+而不是一次替换来减少替换次数(昂贵),则效率会大大提高。
现在,您只需要定义字母数字即可:
str对象,仅ASCII A-Za-z0-9:
re.sub(r'[W_]+', '', s)
str对象,仅区域设置定义的字母数字:
re.sub(r'[W_]+', '', s, flags=re.LOCALE)
unipre对象,所有字母数字:
re.sub(ur'[W_]+', u'', s, flags=re.UNICODE)
str对象的示例:
>>> import re, locale>>> sall = ''.join(chr(i) for i in xrange(256))>>> len(sall)256>>> re.sub('[W_]+', '', sall)'0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'>>> re.sub('[W_]+', '', sall, flags=re.LOCALE)'0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'>>> locale.setlocale(locale.LC_ALL, '')'English_Australia.1252'>>> re.sub('[W_]+', '', sall, flags=re.LOCALE)'0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyzx83x8ax8cx8ex9ax9cx9ex9fxaaxb2xb3xb5xb9xbaxc0xc1xc2xc3xc4xc5xc6xc7xc8xc9xcaxcbxccxcdxcexcfxd0xd1xd2xd3xd4xd5xd6xd8xd9xdaxdbxdcxddxdexdfxe0xe1xe2xe3xe4xe5xe6xe7xe8xe9xeaxebxecxedxeexefxf0xf1xf2xf3xf4xf5xf6xf8xf9xfaxfbxfcxfdxfexff'# above output wrapped at column 80Unipre示例:
>>> re.sub(ur'[W_]+', u'', u'a_b A_Z x80xFF u0404', flags=re.UNICODE)u'abAZxffu0404'



