Python 正则匹配标签中的 中文

1 篇文章 0 订阅

有如下内容:

text = '<div class="comment-content comment-content_new">测试</div> <div class="comment-content comment-content_new">学习正则</div>'

使用正则 匹配出所有的中文。

  • 第一种
p = re.compile(r'([^x00-xff]*)\<\/div\>')

for m in p.finditer(text):
    print(m.group(1))
# 打印结果:

测试
学习正则

这样就是比较的简单,直接是 匹配 Ascii 码大于 255 的那些字符(包括中文符号)

  • 第二种
res = re.findall(u"[\u4e00-\u9fa5]+", str(text))
print(res)
# 打印结果:

['测试', '学习正则']

\u4e00-\u9fa5unicode 编码的中文编码范围,用它来匹配中文也是非常的合适。

还可以在添加一些优化,使得可以匹配出中文的字符。

text = '<div class="comment-content comment-content_new">测试,。、【】、</div> <div class="comment-content comment-content_new">学习正则</div>'

res = re.findall(u"[\u2000-\u206f\u3000-\u303f\u4e00-\u9fef\uff00-\uffef]+", str(text)

print(res)
# 打印结果:

['测试,。、【】、', '学习正则']
# http://www.unicode.org/charts/PDF/U2000.pdf 一般标点
# http://www.unicode.org/charts/PDF/U3000.pdf CJK符号和标点
# http://www.unicode.org/charts/PDF/U4E00.pdf CJK统一表意文字
# http://www.unicode.org/charts/PDF/UFF00.pdf 半宽全宽形状

"[\u2000-\u206f\u3000-\u303f\u4e00-\u9fef\uff00-\uffef]*";


  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值