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)

案例8

posted @   既生喻何生亮  阅读(270)  评论(0编辑  收藏  举报
编辑推荐:
· Java 中堆内存和栈内存上的数据分布和特点
· 开发中对象命名的一点思考
· .NET Core内存结构体系(Windows环境)底层原理浅谈
· C# 深度学习:对抗生成网络(GAN)训练头像生成模型
· .NET 适配 HarmonyOS 进展
阅读排行:
· 用 DeepSeek 给对象做个网站,她一定感动坏了
· DeepSeek+PageAssist实现本地大模型联网
· 手把手教你更优雅的享受 DeepSeek
· Java轻量级代码工程
· 从 14 秒到 1 秒:MySQL DDL 性能优化实战
点击右上角即可分享
微信分享提示