首页 > 编程语言 > 详细

python(5)-正则表达式

时间:2016-03-14 01:28:03      阅读:224      评论:0      收藏:0      [点我收藏+]

技术分享

数量词的贪婪模式与非贪婪模式

正则表达式通常用于在文本中查找匹配的字符串。Python里数量词默认是贪婪的(在少数语言里也可能是默认非贪婪),总是尝试匹配尽可能多的字符;非贪婪的则相反,总是尝试匹配尽可能少的字符。例如:正则表达式"ab*"如果用于查找"abbbc",将找到"abbb"。而如果使用非贪婪的数量词"ab*?",将找到"a"。

 

re.compile()

>>> exp = re.compile("[a-z]")     #生成要匹配的正则对象
>>> m = exp.match(bigtext)       
>>> print(m.group())
b

匹配IP

string = "192.168.0.1"
m = re.match("([0-9]{1,3}\.){3}\d{1,3}", string)
print(m.group())

匹配手机号

#匹配手机号

phone1 = "hey my name is zhangsan, and my phone number is 13651053467"
phone1 = "hey my name is zhangsan, and my phone number is 15811784456"
m = re.search("(1)([3587]\d{9})", phone1)  #第一组匹配第一个数字,第二组匹配第二个数字,第三组匹配剩下的9位数

python(5)-正则表达式

原文:http://www.cnblogs.com/huangxm/p/5274274.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!