Python-正则表达式

Python的正则表达式的模块名字是‘re'

>>> import re

>>> rawString = r'This is a\nnormal string.'

>>> rawString

'This is a\nnormal string.'

>>> string = 'This is a\nnormal string.'

>>> string

'This is a

normal string.'

==================================

>>> match = re.match(r'dog', 'dog cat dog')

>>> match.group(0)

'dog'

 

.match()函数只能从字符串最开始进行匹配

>>> match = re.match(r'cat', 'dog cat dog')

>>> match

>>>

===================================

.search()函数可以在字符串里从左到右自有匹配,不过只能匹配一次,查找到一个匹配项之后就停止

>>> match = re.search(r'cat', 'dog cat dog')

>>> match.group(0)

'cat'

====================================

.findall()函数可以在字符串里,查找到所有匹配项,并放入一个列表中

>>> match = re.findall(r'dog', 'dog cat dog')

>>> match

['dog', 'dog']

>>> match = re.findall(r'cat', 'dog cat dog')

>>> match

['cat']

=====================================

>>> match = re.search(r'dog', 'dog cat dog')

>>> match.start()

0

>>> match.end()

3

.start()与.end()两个函数,可用于告诉该匹配对象在字符串中的开始位置与结束为止

=====================================

>>> contaciInfo = 'Doe, John: 555-1212'

>>> match = re.search(r'(?P<.last>\w+), (?P<first>\w+): (?P<phone>\S+)', contactInfo)

>>> match.group('last')

'Doe'

>>> match.group('first')

'John'

>>> match.group('phone')

'555-1212'

可以直接给分组命名,方便后续使用。不过.findall()函数不适用于命名

>>> re.findall(r'(\w+), (\w+): (\S+)', contactInfo)

[('Doe', 'John', '555-1212')]

====================================================

转载于:https://www.cnblogs.com/yy-is-ing/p/3941516.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值