43 正则中用sub和subn函数搜索与替换 使用split函数分隔字符串 练习题

第10课 正则中用sub和subn函数搜索与替换
# 使用sub和subn函数搜索和替换

'''
sub(正则表达式,要替换的字符串,母字符串)
'''

import re
result = re.sub('Bill','Mike', 'Bill is my son.')
print(result)       # Mike is my son.   把Bill 替换成 Mike

result = re.subn('Bill', 'Mike', 'Bill is my son, I like Bill')
print(result)       # ('Mike is my son, I like Mike', 2)    分组    把Bill 全部替换成 Mike  后面为2次
print(result[0])    # Mike is my son, I like Mike
print('已经替换了{}次'.format(result[1]))    # 已经替换了2次

# 使用'\N'引用匹配字符串的分组
# 1abc 1:abc   2xyz 2:xyz   9hfg 9:hfg
result = re.sub('([0-9])([a-z]+)',r'\1:\2' ,'01-1abc,02-2xyz,03-9hfg')
print(result)   # 01-1:abc,02-2:xyz,03-9:hfg

# 这里面 可以是函数
def fun():
    return r'[\1*\2]'
result = re.subn('([0-9])([a-z]+)',fun() ,'01-1abc,02-2xyz,03-9hfg')
print(result)      # ('01-[1*abc],02-[2*xyz],03-[9*hfg]', 3)
print(result[0])   # 01-[1*abc],02-[2*xyz],03-[9*hfg]
print(result[1])   # 3
第11课 正则中 使用split函数分隔字符串
# 使用split函数分隔字符串

import re
result = re.split(';','Bill;Mike;John')
print(result)     # ['Bill', 'Mike', 'John']

# 至少有1个逗号(,)或分号(;)或点(\.)或空白符空格(\s) *****
result = re.split(r'[,;\.\s]+','a,b,,,d.x,;ok')
print(result)     # ['a', 'b', 'd', 'x', 'ok']

# 用以3个小写字母开头,紧接着一个连字符(-),并以两个数字结尾的字符串作为分隔符
# abc-12
result = re.split('[a-z]{3}-[0-9]{2}','testabc-3213productxyz-45abill')
print(result)         # ['test', '13product', 'abill']
result = re.split('[a-z]{3}-[0-9]{2}','testabc-3213productxyz-45abill',maxsplit=1)
print(result)         # ['test', '13productxyz-45abill']    只分割了一次
第12课 练习题

# 练习题讲解

'''
1.  编写一个正则表达式,匹配这几个单词:bat、Bit、But、hAt、hit、hut。
'''
import re
s1 = '^[bh][aiu]t$'
list =['bat','Bit','But','hAt','hit','hut']
for value in list:
    print(re.match(s1, value,re.I))
print("-------------------")

s2 = '^[bh][aiu]t$'
list =['bat','Bit','But','hAt','hit','hut']
for value in list:
    #print(re.match(s1, value,re.I))
    m = re.match(s2, value, re.I)
    print(m.group())
print("-------------------")

# 练习题讲解
'''
2.  编写一个正则表达式,匹配信用卡号。格式如下:
xxxx xxxx xxxx xxxx,其中x表示0到9的数字。每一组是4个数字,组与组之间需要有至少一个空格。\s+  至少一个空格
1234 4321 5432 1234    # 空白符空格(\s)
'''
import re
s = '^\d{4}\s+\d{4}\s+\d{4}\s+\d{4}$'
list = ['1234 4321 5432 1234','12345 4321 5432 1234']
for value in list:
    print(re.match(s,value,re.I))
'''
结果为第一个是匹配的 第二个是不匹配的 
<re.Match object; span=(0, 19), match='1234 4321 5432 1234'>
None
'''

print("-----------")
# 练习题讲解
'''
3. 编写一个匹配日期的正则表达式,日期格式:YYYY-MM?-DD?。
其中YYYY表示4位的年,MM?表示1位或2位的月,DD?表示1位或2位的日。
而且4位的年必须在2000年以后,包括2000年。
例如,2001-4-5、2004-05-1都符合要求。

'''
import re
s = '2\d{3}-\d{1,2}-\d{1,2}'
print(re.match(s, '2002-12-1'))   # <re.Match object; span=(0, 9), match='2002-12-1'>

ss = '日期1:2012-4-12   日期2:1997-1-4   日期3:2045-1-2'
print(re.findall(s,ss))    # ['2012-4-12', '2045-1-2'] 

猜你喜欢

转载自blog.51cto.com/12445535/2465946