python正则替换中的unicode问题
17-19,结论:对于unicode字符串,要⽤unicode正则字符串查,unicode正则字符串的构成有两个要件,⼀是字符串本⾝由unicode字符构成,⼆是⽤'u'引导(python2);
20-23,结论:对于str字符串,要⽤⼆进制正则字符串查,⽤'r'引导,如果⽤'u'引导,因为并不包含unicode字符,其实际上不起作⽤,相当于'r';
In [17]: %paste
import re
html = u"abcd 32⼈喜欢 efgh"
html = re.sub(ur'(\d+)\u4eba\u559c\u6b22', r'<div class="like">\1</div>', html)
print html
## -- End pasted text --
abcd <div class="like">32</div> efgh
In [18]: %paste
import re
html = u"abcd 32⼈喜欢 efgh"
html = re.sub(r'(\d+)\u4eba\u559c\u6b22', r'<div class="like">\1</div>', html)
print html
## -- End pasted text --
abcd 32⼈喜欢 efgh
In [19]: %paste
import re
html = u"abcd 32⼈喜欢 efgh"
html = re.sub(r'(\d+)\xe4\xba\xba\xe5\x96\x9c\xe6\xac\xa2', r'<div class="like">\1</div>', html)
print html
## -- End pasted text --
abcd 32⼈喜欢 efgh
In [20]: %paste
import re
html = "abcd 32⼈喜欢 efgh"
html = re.sub(r'(\d+)\u4eba\u559c\u6b22', r'<div class="like">\1</div>', html)
print html
## -- End pasted text --unicode所有字符
abcd 32浜哄枩娆?efgh
In [21]: %paste
import re
html = "abcd 32⼈喜欢 efgh"
html = re.sub(ur'(\d+)\u4eba\u559c\u6b22', r'<div class="like">\1</div>', html)
print html
## -- End pasted text --
abcd 32浜哄枩娆?efgh
In [22]: %paste
import re
html = "abcd 32⼈喜欢 efgh"
html = re.sub(r'(\d+)\xe4\xba\xba\xe5\x96\x9c\xe6\xac\xa2', r'<div class="like">\1</div>', html)
print html
## -- End pasted text --
abcd <div class="like">32</div> efgh
In [23]: %paste
import re
html = "abcd 32⼈喜欢 efgh"
html = re.sub(ur'(\d+)\xe4\xba\xba\xe5\x96\x9c\xe6\xac\xa2', r'<div class="like">\1</div>', html)
print html
## -- End pasted text --
abcd <div class="like">32</div> efgh

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。