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

Python-----正则表达式练习

时间:2016-03-17 02:01:50      阅读:299      评论:0      收藏:0      [点我收藏+]

标签:

 1 #-*-coding:utf8-*-
 2 #导入re库文件
 3 import re
 4 from re import findall,search,S
 5 secret_code = hadkfalifexxIxxfasdjifja134xxlovexx23345sdfxxyouxx8dfse
 6 
 7 #.的使用举例 匹配任意字符,换行符\n除外
 8 #a = ‘xy123‘
 9 #b = re.findall(‘x...‘,a)
10 #c = re.findall(‘x..‘,a)
11 #print b
12 #print c
13 
14 # *的使用举例 匹配前一个字符0次或无限次
15 # a = ‘xyxy123xx456xxx789‘
16 # b = re.findall(‘x*‘,a)
17 # print b
18 # [‘x‘, ‘‘, ‘x‘, ‘‘, ‘‘, ‘‘, ‘‘, ‘xx‘, ‘‘, ‘‘, ‘‘, ‘xxx‘, ‘‘, ‘‘, ‘‘, ‘‘]
19 
20 #?的使用举例 匹配前一个字符0次或1次
21 # a = ‘xy123‘
22 # b = re.findall(‘x?‘,a)
23 # print b
24 
25 # #.*的使用举例 贪心算法
26 # b = re.findall(‘xx.*xx‘,secret_code)
27 # print secret_code
28 # print b
29 # # #.*?的使用举例
30 # c = re.findall(‘xx.*?xx‘,secret_code)
31 # print c
32 
33 
34 # #使用括号与不使用括号的差别
35 # d = re.findall(‘xx(.*?)xx‘,secret_code)
36 # print d
37 # for each in d:
38 #     print each
39 # re.S匹配包括换行符
40 # s = ‘‘‘sdfxxhello
41 # xxfsdfxxworldxxasdf‘‘‘
42 #
43 # d = re.findall(‘xx(.*?)xx‘,s,re.S)#,re.S
44 # print d
45 
46 #对比findall与search的区别
47 # s2 = ‘asdfxxIxx123xxlovexxdfd‘
48 # f = re.search(‘xx(.*?)xx123xx(.*?)xx‘,s2).group(2)
49 # print f
50 # f2 = re.findall(‘xx(.*?)xx123xx(.*?)xx‘,s2)
51 # print f2[0][1]
52 
53 #sub的使用举例 替换
54 # s = ‘123rrrrr123‘
55 # output = re.sub(‘123(.*?)123‘,‘123%d123‘%789,s)
56 # print output
57 
58 #演示不同的导入方法
59 # info = findall(‘xx(.*?)xx‘,secret_code,S)
60 # for each in info:
61 #     print each
62 
63 #不要使用compile 多此一举
64 # pattern = ‘xx(.*?)xx‘
65 # new_pattern = re.compile(pattern,re.S)
66 # output = re.findall(new_pattern,secret_code)
67 # re1 = re.findall(‘xx(.*?)xx‘,secret_code,re.S)
68 # print output
69 # print re1
70 
71 #匹配数字
72 # a = ‘asdfasf1234567fasd555fas‘
73 # #b = re.findall(‘\d+‘,a)#[‘1234567‘, ‘555‘]
74 # b = re.findall(‘(\d+)‘,a)
75 # print b

 

Python-----正则表达式练习

标签:

原文地址:http://www.cnblogs.com/codevs/p/5285830.html

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