1 #  ?匹配零次或一次前面的分组。
  2 #  *匹配零次或多次前面的分组。
  3 #  +匹配一次或多次前面的分组。
  4 #  {n}匹配 n 次前面的分组。
  5 #  {n,}匹配 n 次或更多前面的分组。
  6 #  {,m}匹配零次到 m 次前面的分组。
  7 #  {n,m}匹配至少 n 次、至多 m 次前面的分组。
  8 #  {n,m}?或*?或+?对前面的分组进行非贪心匹配。
  9 #  ^spam 意味着字符串必须以 spam 开始。
 10 #  spam$意味着字符串必须以 spam 结束。
 11 #  .匹配所有字符,换行符除外。
 12 #  \d、\w 和\s 分别匹配数字、单词和空白(回车换行、制表符、)。
 13 #  \D、\W 和\S 分别匹配出数字、单词和空格外的所有字符。
 14 #  [abc]匹配方括号内的任意字符(诸如 a、b 或 c)。
 15 #  [^abc]匹配不在方括号内的任意字符。
 16 
 17 import re
 18 rePhoneNumber=re.compile(r"\d\d\d-\d\d\d-\d\d\d\d")# rePhoneNumber现在是 Regex 对象
 19 #查找字符串中模式 search(),查找到之后返回 Match 对象;否则返回None
 20 myMatch=rePhoneNumber.search("My number is 415-555-4242.His number is 4332-666-777")
 21 print(myMatch.group())#415-555-4242,返回实际匹配文本的字符串
 22 
 23 # #findall()方法返回返回一组字符串,包含被查找字符串中的所有匹配
 24 # phoneNumRegex = re.compile(r'\d\d\d-\d\d\d-\d\d\d\d') # has no groups
 25 # phoneNumRegex.findall('Cell: 415-555-9999 Work: 212-555-0000')#['415-555-9999', '212-555-0000']
 26 
 27 
 28 #利用()分组
 29 phoneNumRegex = re.compile(r'(\d\d\d)-(\d\d\d-\d\d\d\d)')
 30 mo = phoneNumRegex.search('My number is 415-555-4242.')
 31 print(mo.group(1))#415
 32 print(mo.group(2))#555-4242
 33 print(mo.group(0))#415-555-4242
 34 print(mo.groups())#('415', '555-4242')
 35 
 36 #用管道匹配多个分组【"|"】,匹配许多表达式中的一个
 37 heroRegex = re.compile (r'Batman|Tina Fey')#将匹配'Batman'或'Tina Fey'。
 38 mo1 = heroRegex.search('Batman and Tina Fey.')
 39 mo1.group()
 40 print(mo1.group())#Batman
 41 
 42 #用 ? 实现可选匹配,不论这段文本在不在,正则表达式都会认为匹配
 43 batRegex = re.compile(r'Bat(wo)?man')
 44 mo1 = batRegex.search('The Adventures of Batman')
 45 mo1.group()
 46 print(mo1.group())#(wo)?部分表明,模式 wo 是可选的分组。该正则表达式匹配的文本中,wo 将出现零次或一次
 47 
 48 phoneRegex = re.compile(r'(\d\d\d-)?\d\d\d-\d\d\d\d')#可以匹配  415-555-4242  或 555-4242
 49 mo1 = phoneRegex.search('My number is 415-555-4242')
 50 mo2 = phoneRegex.search('My number is 555-4242')
 51 print(mo1.group())#415-555-4242
 52 print(mo2.group())#555-4242
 53 
 54 #用 * 号匹配零次或多次
 55 phoneRegex = re.compile(r'(\d\d\d-)*\d\d\d-\d\d\d\d')
 56 mo1 = phoneRegex.search('My number is 415-555-4242')
 57 mo2 = phoneRegex.search('My number is 555-4242')
 58 print(mo1.group())#415-555-4242
 59 print(mo2.group())#555-4242
 60 
 61 # 用 + 号匹配一次或多次,*意味着“匹配零次或多次”,+(加号)则意味着“匹配一次或多次”。
 62 # * 号不要求分组出现在匹配的字符串中,但加号不同,加号前面的分组必须“至少出现一次”。这不是可选的。
 63 # r'Bat(wo)+man',要求 wo 至少出现一次
 64 
 65 #用 {} 花括号匹配特定次数,(Ha){3}匹配字符串'HaHaHa',但不会匹配'HaHa'
 66 #(Ha){3,5},匹配 3次、4次、5次; 默认匹配最长的(贪心模式);加问号为非贪心模式,匹配最短的(Ha){3,5}?
 67 #(Ha){3,}将匹配 3 次或更多次实例
 68 #(Ha){,5}将匹配 0 到 5 次实例
 69 
 70 
 71 #findall()方法返回返回一组字符串,包含被查找字符串中的所有匹配
 72 phoneNumRegex = re.compile(r'\d\d\d-\d\d\d-\d\d\d\d') # has no groups
 73 strList=phoneNumRegex.findall('Cell: 415-555-9999 Work: 212-555-0000')
 74 print(strList)#['415-555-9999', '212-555-0000'],无分组,返回字符串列表
 75 
 76 #如果在正则表达式中有分组,那么 findall 将返回元组的列表。每个元组表示一个找
 77 #到的匹配,其中的项就是正则表达式中每个分组的匹配字符串
 78 
 79 phoneNumRegex = re.compile(r'(\d\d\d)-(\d\d\d)-(\d\d\d\d)') # has groups
 80 tupleList=phoneNumRegex.findall('Cell: 415-555-9999 Work: 212-555-0000')
 81 print(tupleList)   #[('415', '555', '1122'), ('212', '555', '0000')],有分组,返回字符串元组列表
 82 
 83 #缩写类字符分类
 84 #\d:代表任意数字,是(0|1|2|3|4|5|6|7|8|9)的缩写
 85 #\D:除 0 到 9 的数字以外的任何字符
 86 #\w:任何字母、数字或下划线字符(可以认为是匹配“单词”字符)
 87 #\W: 除字母、数字和下划线以外的任何字符
 88 #\s:空格、制表符或换行符(可以认为是匹配“空白”字符)
 89 #\S:除空格、制表符和换行符以外的任何字符
 90 
 91 xmasRegex = re.compile(r'\d+\s\w+')#数字串+空白+字母串
 92 xmasRegex.findall('12 drummers, 11 pipers, 10 lords, 9 ladies, 8 maids, \
 93 7swans, 6 geese, 5 rings, 4 birds, 3 hens, 2 doves, 1 partridge')
 94 
 95 # ['12 drummers', '11 pipers', '10 lords', '9 ladies', '8 maids', '7 swans', '6
 96 # geese', '5 rings', '4 birds', '3 hens', '2 doves', '1 partridge']
 97 
 98 #建立自己的字符分类
 99 #例如,字符分类[aeiouAEIOU]将匹配所有元音字符,不论大小写。
100 #短横表示字母或数字的范围,例如,字符分类[a-zA-Z0-9]将匹配所有小写字母、大写字母和数字。
101 #通过在字符分类的【左方括号后】加上一个插入字符(^),就可以得到“非字符类”。
102 consonantRegex = re.compile(r'[^aeiouAEIOU]')#表示匹配非元音
103 
104 #匹配开头【^】,可以在正则表达式的【开始处】使用插入符号(^),表明匹配必须发生在被查找文本开始处。
105 beginsWithHello = re.compile(r'^Hello')
106 beginsWithHello.search('Hello world!')
107 
108 #匹配结尾【$】
109 #正则表达式 r'\d$'匹配以数字 0 到 9 结束的字符串
110 endsWithNumber = re.compile(r'\d$')
111 print(endsWithNumber.search('Your number is 42'))#<_sre.SRE_Match object; span=(16, 17), match='2'>
112 # endsWithNumber.search('Your number is forty two.') == None
113 #从开始到结束都是数字的字符串【'^\d+$】
114 wholeStringIsNum = re.compile(r'^\d+$')
115 print(wholeStringIsNum.search('1234567890'))#<_sre.SRE_Match object; span=(0, 10), match='1234567890'>
116 print(wholeStringIsNum.search('1234567890aaa'))#None
117 
118 #通配字符[.],它匹配除了换行之外的个一个所有字符;要匹配真正的句点,就是用倒斜杠转义:\.
119 atRegex = re.compile(r'.at')
120 atRegex.findall('The cat in the hat sat on the flat mat.')
121 #['cat', 'hat', 'sat', 'lat', 'mat']
122 
123 #匹配任意文本除了换行符 【.*】:.  为一个字符,*为匹配0次或多次,必需要有值,否则报错; 默认贪心模式;非贪心模式加?
124 nameRegex = re.compile(r'First Name: (.*) Last Name: (.*)')
125 mo = nameRegex.search('First Name: lily Last Name: Sweigart')
126 # mo = nameRegex.search('First Name: All Last Name: Sweigart')
127 print(mo.group(1))#'lily'
128 print(mo.group(2))#'Sweigart'
129 
130 nameRegex = re.compile(r'First Name: (.*) Last Name: (.*)')
131 mo = nameRegex.search('First Name: lily\n Last Name: Sweigart')
132 # mo = nameRegex.search('First Name: All Last Name: Sweigart')
133 # print(mo.group(1))#'lily'
134 # print(mo.group(2))#'Sweigart'
135 
136 nongreedyRegex = re.compile(r'<.*?>')#“匹配一个左尖括号,接下来是任意字符,接下来是一个右尖括号,非贪心模式
137 mo = nongreedyRegex.search('<To serve man> for dinner.>')#对右肩括号有两种可能的匹配
138 print(mo.group())#<To serve man>
139 
140 nongreedyRegex = re.compile(r'<.*>')#贪心模式
141 mo = nongreedyRegex.search('<To serve man> for dinner.>')
142 print(mo.group())#<To serve man> for dinner.>
143 
144 #  不区分大小写的匹配,向 re.compile()传入 re.IGNORECASE 或 re.I,作为第二个参数
145 robocop = re.compile(r'robocop', re.I)
146 robocop.search('RoboCop is part man, part machine, all cop.').group()
147 #'RoboCop'
148 robocop.search('ROBOCOP protects the innocent.').group()
149 #'ROBOCOP'
150 robocop.search('Al, why does your programming book talk about robocop so much?').group()
151 #'robocop'
152 
153 #查找后替换
154 namesRegex = re.compile(r'Agent \w+')
155 namesRegex.sub('CENSORED', 'Agent Alice gave the secret documents to Agent Bob.')
156 #'CENSORED gave the secret documents to CENSORED.'
157 
158 phoneRegex = re.compile(r'((\d{3}|\(\d{3}\))?(\s|-|\.)?\d{3}(\s|-|\.)\d{4}(\s*(ext|x|ext.)\s*\d{2,5})?)')
159 phoneRegex = re.compile(r'''(
160 (\d{3}|\(\d{3}\))? # area code
161 (\s|-|\.)? # separator
162 \d{3} # first 3 digits
163 (\s|-|\.) # separator
164 \d{4} # last 4 digits
165 (\s*(ext|x|ext.)\s*\d{2,5})? # extension
166 )''', re.VERBOSE)
167 
168 # Create email regex.
169 emailRegex = re.compile(r'''(
170  [a-zA-Z0-9._%+-]+ # username
171  @ # @ symbol
172  [a-zA-Z0-9.-]+ # domain name
173 (\.[a-zA-Z]{2,4}) # dot-something
174 )''', re.VERBOSE)

 

ode

 

原文地址:http://www.cnblogs.com/ltsgsh/p/16791747.html

1. 本站所有资源来源于用户上传和网络,如有侵权请邮件联系站长! 2. 分享目的仅供大家学习和交流,请务用于商业用途! 3. 如果你也有好源码或者教程,可以到用户中心发布,分享有积分奖励和额外收入! 4. 本站提供的源码、模板、插件等等其他资源,都不包含技术服务请大家谅解! 5. 如有链接无法下载、失效或广告,请联系管理员处理! 6. 本站资源售价只是赞助,收取费用仅维持本站的日常运营所需! 7. 如遇到加密压缩包,默认解压密码为"gltf",如遇到无法解压的请联系管理员! 8. 因为资源和程序源码均为可复制品,所以不支持任何理由的退款兑现,请斟酌后支付下载 声明:如果标题没有注明"已测试"或者"测试可用"等字样的资源源码均未经过站长测试.特别注意没有标注的源码不保证任何可用性