import re #导入正则表达式模块
# 在py中match()
# re.match(pattern,string,[flags])
# w 匹配字母数字下划线或者数字 +匹配前面字符的一次或者多次
# r 代表原始字符,防止出现转义
pattern = r'mr_w+'
string = "MR_CODE mr_code"
match = re.match(pattern,string,re.I) # i表示不区分大小写
print(match)
#ps <re.Match object; span=(0, 7), match='MR_CODE'>
# 因为不匹配空格,故未匹配到 mr_code
# 将空格去掉后,MR_CODEmr_code 则可匹配到 MR_CODEmr_code
pattern2 = r'mr_w+'
string2 = "sssMR_CODE mr_code"
match2 = re.match(pattern2,string2,re.I) # i表示不区分大小写
print(match2)
# 若未匹配到,返回None
# 在py中search()
pattern3 = r'mr_w+'
string3 = "sssMR_CODE mr_code"
search = re.search(pattern3,string3,re.I) # i表示不区分大小写
print(search)
# <re.Match object; span=(3, 10), match='MR_CODE'>
pattern4 = r'mr_w+'
string4 = "ssssssMR_CODE mr_code"
search2 = re.search(pattern4,string4,re.I) # i表示不区分大小写
print(search2)
# <re.Match object; span=(6, 13), match='MR_CODE'>
# 在py中findall()
pattern5 = r'mr_w+'
string5 = "ssssssMR_CODE mr_code"
search5 = re.findall(pattern5,string5,re.I) # i表示不区分大小写
print(search5)
print("findall()")
# 在py中sub() 替换
pattern6 = r'1[34578]d{9}'
string6 = "中奖号码为:89332,联系电话:13611111111"
search6 = re.sub(pattern6,'1我爱学py',string6) # i表示不区分大小写
print("sub()")
print(search6)
# 中奖号码为:89332,联系电话:1我爱学py