码迷,mamicode.com
首页 > 编程语言 > 详细

Python正则表达式符号与方法

时间:2016-04-12 14:25:50      阅读:178      评论:0      收藏:0      [点我收藏+]

标签:正则表达式   python   

导入re库文件

import re

 from re import findall,search,S


secret_code = ‘hadkfalifexxIxxfasdjifja134xxlovexx23345sdfxxyouxx8dfse‘   #红色为待带抓取内容


.的使用举例

 a = ‘xy123‘

 b = re.findall(‘x...‘,a)

 print b          #执行后返回xy12,x...中“.”代表占位符,几个点就取x后几位


*的使用举例

 a = ‘xyxy123‘

 b = re.findall(‘x*‘,a)

 print b      

#执行后返回[‘x‘, ‘‘, ‘x‘, ‘‘, ‘‘, ‘‘, ‘‘],x*代表生成匹配x(0-无穷次)的列表,不匹配的生成空字符串‘‘



?的使用举例

 a = ‘xy123x‘

 b = re.findall(‘x?‘,a)

 print b     

 #执行后返回[‘x‘, ‘‘, ‘‘, ‘‘, ‘‘, ‘x‘, ‘‘],x?代表生成匹配x(0-无穷次)的列表,和x*的区别是列表最后加一个空字符串‘‘



‘‘‘上面的内容全部都是只需要了解,需要掌握的只有下面这一种组合方式(.*?)‘‘‘


 #.*的使用举例

 b = re.findall(‘xx.*xx‘,secret_code)

 print b

 # #.*?的使用举例

 c = re.findall(‘xx.*?xx‘,secret_code)

 print c




 #使用括号与不使用括号的差别

 d = re.findall(‘xx(.*?)xx‘,secret_code)

 print d

 for each in d:

     print each


 s = ‘‘‘sdfxxhello

 xxfsdfxxworldxxasdf‘‘‘


 d = re.findall(‘xx(.*?)xx‘,s,re.S)

 print d



对比findall与search的区别

 s2 = ‘asdfxxIxx123xxlovexxdfd‘

 # f = re.search(‘xx(.*?)xx123xx(.*?)xx‘,s2).group(2)

 # print f

 f2 = re.findall(‘xx(.*?)xx123xx(.*?)xx‘,s2)

 print f2[0][1]


sub的使用举例

 s = ‘123rrrrr123‘

 output = re.sub(‘123(.*?)123‘,‘123%d123‘%789,s)

 print output


演示不同的导入方法

 info = findall(‘xx(.*?)xx‘,secret_code,S)

 for each in info:

     print each


不要使用compile

 pattern = ‘xx(.*?)xx‘

 new_pattern = re.compile(pattern,re.S)

 output = re.findall(new_pattern,secret_code)

 print output


匹配数字

a = ‘asdfasf1234567fasd555fas‘

b = re.findall(‘(\d+)‘,a)

print b


本文出自 “My Space” 博客,转载请与作者联系!

Python正则表达式符号与方法

标签:正则表达式   python   

原文地址:http://coolucky.blog.51cto.com/11370079/1762935

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!