Python正则表达式---全部能匹配的子串迭代器finditer及findall及以中文匹配部分中文 Python正则表达式---全部能匹配的子串迭代器finditer及findall及以中文匹配部分中文

Python正则表达式---全部能匹配的子串迭代器finditer及findall及以中文匹配部分中文

一、正则匹配:findall,finditer

findall(string[, pos[, endpos]]) | re.findall(pattern, string[, flags]):搜索string,以列表形式返回全部能匹配的子串。

finditer(string[, pos[, endpos]]) | re.finditer(pattern, string[, flags]):搜索string,返回一个顺序访问每一个匹配结果(Match对象)的迭代器。

 

[python]  view plain  copy
  1. <span style="font-size:18px;">#coding:utf-8  
  2. import re  
  3. s='[0-9]{4}年([0-9]{1,2}月)?([0-9]{1,2}日)?'  
  4. st_1=''''' 
  5. 男,1941年3月生于河北省涿州市; 
  6. 出生日期:1988年12月15日 出生地:黑龙江省齐齐哈 
  7. 编辑(1975年——),中国青年 
  8. 族人,1985年10月13日出生于 陕西 省。 2003年 
  9. '''  
  10. #-----------------对比findall和finditer-------------------  
  11. #-------找出字符里面所有的数字  
  12. p = re.compile(r'\d+')  
  13. print p.findall('one1two2three3four4')  
  14. #-------  
  15. for m in p.finditer('one1two2three3four4'):  
  16.     print m.group(),  
  17. #-------找出所有年月日时间  
  18. print ''  
  19. p=re.compile(r'[0-9]{4}年([0-9]{1,2}月)?([0-9]{1,2}日)?')  
  20. print p.findall(st_1)  
  21. #-------  
  22. for m in p.finditer(st_1):  
  23.     print m.group()</span>  


二、正则表达式匹配部分中文:

卤主的中文文本是utf-8格式的,想要匹配某个中文到某个中文之间的词,却是弄得很是麻烦,终究发现也是挺简单的:

[python]  view plain  copy
  1. In [3]: import re  
  2.   
  3. In [4]: a = u"“你不去我也不去” 王琳佳和叶梦圆手拉手上了飞机(组图)-新闻频道-手机 搜狐"  
  4.   
  5. In [5]: p = re.compile(u"图\).*")  
  6.   
  7. In [6]: p.findall(a)  
  8. Out[6]: [u'\u56fe)-\u65b0\u95fb\u9891\u9053-\u624b\u673a \u641c\u72d0']  
本来应该是: p =re.compile(r"图\).*"),但是正则里面包含中文,需要用u进行编译。

猜你喜欢

转载自blog.csdn.net/qq_30868235/article/details/80641862
今日推荐