Python实验7:深入学习Python正则表达式

第1关:正则表达式基础知识

import re
text = input()
#********** Begin *********#
#1.匹配字符单词 Love
print(re.findall(r'Love', text))
#2.匹配以 w 开头的完整单词
print(re.findall(r'\bw\w*', text))
#3.查找三个字母长的单词(提示:可以使用{m,n}方式)
print(re.findall(r'\b\w{3}\b', text))
#********** End **********#

第2关:re 模块中常用的功能函数(一)

import re
text = input()
#********** Begin *********#
#1.用compile方法,匹配所有含字母i的单词
pattern1 = re.compile(r'\b\w*i\w*\b')
print(pattern1.findall(text))

#2.在字符串起始位置匹配字符The是否存在,并返回被正则匹配的字符串
pattern2 = re.compile(r'The')
match2 = pattern2.match(text)
if match2:
    print(match2.group())
#3.在整个字符串查看字符is是否存在,并返回被正则匹配的字符串
pattern3 = re.compile(r'is')
match3 = pattern3.search(text)
if match3:
    print(match3.group())
#********** End **********#

第3关:re 模块中常用的功能函数(二)

import re
text = input()
#********** Begin *********#
#1.匹配以t开头的所有单词并显示
itext = re.finditer( r'\bt\w+', text)
for match in itext:
    print(match.group())
#2.用空格分割句子
print(re.split(r'\s+', text))
#3.用‘-’代替句子中的空格 
print(re.sub(r'\s+', '-', text ))
#4.用‘-’代替句子中的空格,并返回替换次数
print(re.subn(r'\s+', '-', text ))
#********** End **********#

物联沃分享整理
物联沃-IOTWORD物联网 » Python实验7:深入学习Python正则表达式

发表评论