通常我们可以使用 repr()函数查看字串的原始格式。这对于写正则表达式有所帮助。
UTF-8 是变长的,1-6个字节,少数是汉字每个占用3个字节,多数占用4个字节,正则式为[\x80-\xff]{3}
re.match(), re.search 。
两个函数的匹配过程完全一致,只是起点不同。
match只从字串的开始位置进行匹配,如果失败,它就此放弃;
而search则会锲而不舍地完全遍历整个字串中所有可能的位置,直到成功地找到一个匹配,或者搜索完字串,以失败告终。
如果你了解match的特性(在某些情况下比较快),大可以自由用它;如果不太清楚,search通常是你需要的那个函数。
从一堆文本中,找出所有可能的匹配,以列表的形式返回,这种情况用findall()这个函数。
如果字串不是unicode的,可以使用unicode()函数转换之。如果你知道源字串的编码,可以使用newstr=unicode(oldstring, original_coding_name)的方式转换
# -*- coding: utf-8 -*-
import sys
import re
reload(sys)
sys.setdefaultencoding('utf8')
s="""
en: Regular expression is a powerful tool for manipulating text.
zh: 汉语是世界上最优美的语言,正则表达式是一个很有用的工具
jp: 正規表現は非常に役に立つツールテキストを操作することです。
jp-char: あアいイうウえエおオ
kr:정규 표현식은 매우 유용한 도구 텍스트를 조작하는 것입니다.
"""
print "原始utf8字符"
#utf8
print "--------"
print repr(s)
print "--------\n"
#非ansi
re_words=re.compile(r"[\x80-\xff]+")
m = re_words.search(s,0)
print "非ansi字符"
print "--------"
print m
print m.group()
print "--------\n"
#unicode
s = unicode(s)
print "原始unicode字符"
print "--------"
print repr(s)
print "--------\n"
#unicode chinese
re_words = re.compile(u"[\u4e00-\u9fa5]+")
m = re_words.search(s)
print "unicode 中文"
print "--------"
print m
print m.group()
res = re.findall(re_words, s) # 查询出所有的匹配字符串
if res:
print "There are %d parts:\n"% len(res)
for r in res:
print "\t",r
print
print "--------\n"
#unicode korean
re_words=re.compile(u"[\uac00-\ud7ff]+")
m = re_words.search(s,0)
print "unicode 韩文"
print "--------"
print m
print m.group()
print "--------\n"
#unicode japanese katakana
re_words=re.compile(u"[\u30a0-\u30ff]+")
m = re_words.search(s,0)
print "unicode 日文 片假名"
print "--------"
print m
print m.group()
print "--------\n"
#unicode japanese hiragana
re_words=re.compile(u"[\u3040-\u309f]+")
m = re_words.search(s,0)
print "unicode 日文 平假名"
print "--------"
print m
print m.group()
print "--------\n"
#unicode cjk Punctuation
re_words=re.compile(u"[\u3000-\u303f\ufb00-\ufffd]+")
m = re_words.search(s,0)
print "unicode 标点符号"
print "--------"
print m
print m.group()
print "--------\n"
匹配中文简体和繁体: ^[\u4E00-\u9FFF]+$
匹配中文简体: ^[\u4E00-\u9FA5]+$
匹配日文平假名: ^[\u3040-\u309f]+$
匹配日文片假名: ^[\u30a0-\u30ff]+$
匹配韩文: ^[\uac00-\ud7ff]+$