Python3正则表达式(4)
正则表示式的子模式
使用()表示一个子模式,括号中的内容作为一个整体出现。
(red)+ ==> redred, redredred, 等多个red重复的情况
子模式的扩展语法
案例1
telNumber = 'Suppose my Phone No. is 0535-1234567, yours is 010-12345678, his is 025-87654321.' pattern = re.compile(r'(\d{3,4})-(\d{7,8})') pattern.findall(telNumber)
结果:
[('0535', '1234567'), ('010', '12345678'), ('025', '87654321')]
match对象的主要方法
案例2
m = re.match(r'(\w+) (\w+)', "Hello Bright, Good!") print('返回整个模式内容:{0}'.format(m.group(0))) print('返回第一个子模式内容:{0}'.format(m.group(1))) print('返回第二个子模式内容:{0}'.format(m.group(2))) print('返回指定的多个子模式内容:{0}'.format(m.group(1, 2)))
结果:
返回整个模式内容:Hello Bright 返回第一个子模式内容:Hello 返回第二个子模式内容:Bright 返回指定的多个子模式内容:('Hello', 'Bright')
案例3
exampleString = """There shoule be one -- and preferably only one -- obvious way to do it. Althought that way may not be obvious at first unless you're Dutch. Now is better than never. Although never is offten better than right now.""" pattern1 = re.compile(r'(?<=\w\s)never') matchResult1 = pattern1.search(exampleString) print('查找句子末尾的单词在整个字符串中跨度:{0}'.format(matchResult1.span())) pattern2 = re.compile(r'(?:is\s)better(\sthan)') matchResult2 = pattern2.search(exampleString) print('查找句子末尾的单词在整个字符串中跨度:{0}'.format(matchResult2.span())) print('查找整个模式:{0}'.format(matchResult2.group(0))) print('查找第一个字模式:{0}'.format(matchResult2.group(1)))
结果:
查找句子末尾的单词在整个字符串中跨度:(160, 165) 查找句子末尾的单词在整个字符串中跨度:(145, 159) 查找整个模式:is better than 查找第一个字模式: than
案例4
m = re.match(r"(?P<first_name>\w+) (?P<last_name>\w+)", 'Malcolm Reynolds') print('使用子模式名字打印第1个:{0}'.format(m.group('first_name'))) print('使用子模式名字打印第2个:{0}'.format(m.group('last_name')))
结果
使用子模式名字打印第1个:Malcolm 使用子模式名字打印第2个:Reynolds
案例5
m = re.match(r'(\d+)\.(\d+)', "24.1456") m.groups()
结果
('24', '1456')
案例6
m = re.match(r"(?P<first_name>\w+) (?P<last_name>\w+)", 'Malcolm Reynolds') m.groupdict()
结果
{'first_name': 'Malcolm', 'last_name': 'Reynolds'}
案例7
exampleString = """There shoule be one -- and preferably only one -- obvious way to do it. Althought that way may not be obvious at first unless you're Dutch. Now is better than never. Although never is offten better than right now.""" pattern = re.compile(r'(?<=\w\s)never(?=\s\w)') # 查找不在句子开头和结尾的never matchResult = pattern.search(exampleString) matchResult.span()
结果
(176, 181)
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步