python正则表达式的使用方法

python正则表达式的使用方法

python提供正则表达式的库。

import re

re库中提供的compile,match,search,split,findall是常用的方法。

compile

将正则表达式模式编译成一个正则表达式的对象,用于使用它去匹配match和search方法,使用这个函数的优点就是可以
在单个程序中可以重复的使用。

prog = re.compile(parrent)
result = prog.match(string)
# 相当于
result = re.match(pattern, string)

match

re.match(parrent, string, flag=0)

适用于在字符串的开头的零个或更多字符匹配正则表达式,将返回一个MatchObject的实例,如果没有匹配的字符串,则返回None。
match,只能匹配单行,如果需要匹配的字符串是多行的,也只匹配第一行。

import re

resouce = 'lee lee lee '
prog = re.compile(r'le+')

print type(prog)

result = prog.match(resouce)

print result.group()
'''output
<type '_sre.SRE_Pattern'>
<_sre.SRE_Match object at 0x000000000304A510>
lee
'''
re.search(pattern, string, flag=0)

扫描字符串,寻找第一个由正则表达式产生匹配的位置,返回一个MatchObject实例,返回None说明字符串中没有匹配的子串。

split

re.split(pattern, string, maxsplit=0, flag=0)

把字符串根据正则表达式进行拆分,放在一个list中。

import re

resouce = 'tee lee lee '
prog = re.compile(r'\W+')

print type(prog)

result = prog.split(resouce)

print result
'''output
<type '_sre.SRE_Pattern'>
['tee', 'lee', 'lee', '']
'''

findall

re.findall(pattern, string, flag=0)

从左向右的扫描,匹配按照发现的顺序返回到一个list中,空匹配则就返回一个空的list。

import re

resouce = 'tee lee lee '
prog = re.compile(r'le+')

print type(prog)

result = prog.findall(resouce)

print result
'''output
<type '_sre.SRE_Pattern'>
['lee', 'lee']
'''
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值