

接下来看两个简单的例子:
一、要求:使用正则表达式提取字符串中的电话号码
基本思路:使用模块re的findall()函数在字符串中查找所有符合特定模式的内容
import re
text = 'my phone number is 456789-5556, yours is 5653-7898, his is 898-456123'
matchResult = re.findall(r'(\d+)-(\d+)', text)
for item in matchResult:
print(item[0], item[1], sep='-')
二、假设有一句英文,其中某个单词中有个不在两端的字母误写作大写,编写程序使
用正则表达式进行检査和纠正为小写。注意,不要影响每个单词两端的字母
import re
s = 'I am not a roBot'
s_list = s.split(" ")
a = re.findall('[a-z]+[A-Z][a-z]+',s)
result = a[0]
tmp = list(result)
for i in range(0,len(tmp)):
if(ord(tmp[i])<97):
if(i != 0 or i != len(tmp)-1):
tmp[i] = chr(ord(tmp[i])+32)
newResult = "".join(tmp)
standPoint = s_list.index(result)
s_list[standPoint] = newResult
s = " ".join(s_list)
print(s)