Python中的正则表达式

基于Python 2.7

这里写图片描述
这里写图片描述

#!/usr/bin/env python
# -*- encoding=utf-8 -*-

import re
s = 'ABC\\-001'  #对应 'ABC\-001'
s = r'ABC\-001'  #加r前缀,就不用考虑转义的问题了。
print re.match('^\d{3}\-\d{3,8}$','010-12345')
# 匹配成功返回一个Match对象,否则返回None.

#re.match()的常见写法
'''
test = '输入字符串'
if re.match('正则表达式', test):
    print 'ok'
else:
    print 'failed'
'''

#re.split()函数的使用
print re.split('\s+','a b   c')
# ['a', 'b', 'c']
print re.split('[\s\,]+','a,b, c  d')
#['a', 'b', 'c', 'd']
print re.split('[\s\,\;]+','a,b;; c   d')
#['a', 'b', 'c', 'd']

#提取子串,用()表示要提取的分组
m = re.match('^(\d{3})-(\d{3,8})$','010-12345')
print m.group(0) #原始字符串
print m.group(1) #第一个子串
print m.group(2) #第二个子串

这里写图片描述

通过预编译提高效率

这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值