python 正则表达式,函数说明

1,findall(pattern,string)
返回所有符合pattern的字符串,返回值是列表的格式;如果匹配有多个分组,那么列表的元素是一个元组
key="my w2014-12-12orld helLO a2015-10-10ahello"
pat=re.compile("(\d+)-(\d+)-(\d+)",re.I)
result=pat.findall(key)
print result


返回 => [('2014', '12', '12'), ('2015', '10', '10')]


2,match(pattern,string)
返回字符串中开头匹配的部分,需要从起始位置开始匹配


3,search(pattern,string)
返回字符串中第一个匹配的部分
key="my w2014-12-12orld helLO a2015-10-10ahello"
pat=re.compile("(\d{4})-(\d+)-(\d+)",re.I)
result=pat.search(key).groups()
print result


=> ('2014', '12', '12')


    key = "my w2014-12-12orld helLO a2015-10-10ahello"
    pat = re.compile(".*(\d{4})-(\d+)-(\d+)", re.I)
    result = pat.match(key).groups()
    print result
=> ('2015', '10', '10')


4,split(pattern,string) 根据pattern 出现的位置拆分string,返回一个列表
    key = "my w2014-12-12orld helLO a2015-10-10ahello"
    pat = re.compile("\d+-\d+-\d+", re.I)
    result=pat.split(key)
    print result


=> ['my w', 'orld helLO a', 'ahello']


5,sub就是一般的replace函数,只是匹配部分使用的是正则而已,返回的是字符串
    p="apple|orange|banala"
    key="apple are good,orange are delicious,banala are yellow"
    result=re.compile(p,re.I).sub("fruit",key)
    print result


=> fruit are good,fruit are delicious,fruit is yellow
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值