Python高级编程----正则表达式

#!/usr/bin/python
#-*- coding:utf-8 -*-

'''
Created on 2016年6月25日

@author: Administrator
'''

'''
Python高级编程---正则表达式

#http://www.runoob.com/python/python-reg-expressions.html
'''

import re

#re.match(pattern, string, flags)
'''
参数说明:
pattern:匹配的正则表达式
string:要匹配的字符串
flags:标志位,用于控制正则表达式的匹配方式

匹配对象方法:
group(num=0):匹配的整个表达式的字符串,group() 可以一次输入多个组号,在这种情况下它将返回一个包含那些组所对应值的元组。
groups():返回一个包含所有小组字符串的元组,从 1 到 所含的小组号。
'''

#实例一
def examp01():

#在起始位置匹配
print(re.match('www', 'www.runoob.com').span())
#不在起始位置匹配
print(re.match('com', 'www.runoob.com'))


#实例二
def examp02():
line = "Cats are smarter then dogs dogs2"

#re.match() :只匹配字符串的开始,如果字符串开始不符合正则表达式,则匹配失败,函数返回None
matchObj = re.match(r'(.*) are (.*?) .*', line, re.M|re.I)
if matchObj:
print "matchObj.group():", matchObj.group()
print "matchObj.groups():", matchObj.groups()
print "matchObj.group(1):", matchObj.group(1,2)
print "matchObj.group(2):", matchObj.group(2)
else:
print "No match!"


#re.search():匹配整个字符串,直到找到一个匹配。
matchObj = re.search(r'dogs', line, re.M|re.I)
if matchObj:
print "search----> matchObj.group():", matchObj.group()

else:
print "No match"


#检索和替换
#re.sub(pattern, repl, string, count, flags)

def examp03():
phone = "2004-959-559 # This is Phone Number"

num = re.sub(r'#.*$', "", phone)
print "Phone Num:" , num

#将任意非数字替换为 空
num = re.sub(r'\D', "", phone)
print "Phone Num:" , num


#正则表达式,可选标志位
'''
re.I 使匹配对大小写不敏感
re.L 做本地化识别(locale-aware)匹配
re.M 多行匹配,影响 ^ 和 $
re.S 使 . 匹配包括换行在内的所有字符
re.U 根据Unicode字符集解析字符。这个标志影响 \w, \W, \b, \B.
re.X 该标志通过给予你更灵活的格式以便你将正则表达式写得更易于理解。
'''


if __name__ == '__main__':
examp03()
















-------2016-06-25 10:00
@modaokeng.yongtaixincun.baiyunqu.guangzhoushi.guangdongsheng
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值