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

 
 
 
 

转载于:https://www.cnblogs.com/brightyuxl/p/9242085.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值