python正则典型例子

1. str ="abcdefg123213qwe",匹配以abc开头,以qwe结尾,要怎样写呢?

正解:m = re.match('^abc(.*?)qwe$','abcdefg123213qwe')

>>> m = re.match('^abc(.*?)qwe$','abcdefg123213qwe')
>>> m.group()
'abcdefg123213qwe'
>>> m.group(0)
'abcdefg123213qwe'
>>> m.group(1)
'defg123213'
>>> m.group(2)

Traceback (most recent call last):
  File "<pyshell#22>", line 1, in <module>
    m.group(2)
IndexError: no such group

2. contactInfo = 'Doe, John: 555-1212',进行分组匹配。

match = re.search(r'(\w+), (\w+): (\S+)', contactInfo)

>>> contactInfo = 'Doe, John: 555-1212'
>>> match = re.search(r'(\w+), (\w+): (\S+)', contactInfo)
>>> match.group(0)
'Doe, John: 555-1212'
>>> match.group()
'Doe, John: 555-1212'
>>> match.group(0)
'Doe, John: 555-1212'
>>> match.group(1)
'Doe'
>>> match.group(2)
'John'
>>> match.group(3)
'555-1212'

组的序数从1开始的原因是因为第0个组被预留来存放所有匹配对象

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值