2017年12月13日星期三

正则表达式,python re包

一.正则表达式

1.正则表达式是什么?
正则表达式(Regular Expression)是一种文本模式,包括普通字符(例如,a 到 z 之间的字母)和特殊字符(称为"元字符")。
正则表达式使用单个字符串来描述、匹配一系列匹配某个句法规则的字符串

2.为什么使用正则表达式
 1. 测试字符串模式(可以测试输入字符串,已查看字符串内是否出现电话号码模式或信用卡号码模式,称为数据验证)
 2. 替换文本(可以使用正则表达式来识别文档中的特定文本,完全删除该文本或者用其他文本替换)
 3.基于模式匹配从字符串中提取子字符串

3. 正则表达式语法
1. +   匹配 runoob、runooob、runoooooob
2. × 


二.Python正则表达式 

1. Python中的正则表达式
python自1.5版本增加了re模块,它提供了Perl风格的正则表达式模式
re模块使Python拥有全部的正则表达式功能

2.Re的函数介绍

  2.1 匹配功能
1.re.match(pattern, string, flags=0)   匹配成功返回匹配对象,否则返回None

eg1.
#!/usr/bin/python 
 # -*- coding: UTF-8 -*-  
import re  
print(re.match('www', 'www.runoob.com').span()) # 在起始位置匹配 print(re.match('com', 'www.runoob.com'))               # 不在起始位置匹配
运行结果:
(0, 3)
None

eg2.
#!/usr/bin/python  
import re 
line = "Cats are smarter than dogs"  
matchObj = re.match( r'(.*) are (.*?) .*', line, re.M|re.I) 
if matchObj:  
print "matchObj.group() : ", matchObj.group() 
print "matchObj.group(1) : ", matchObj.group(1) 
print "matchObj.group(2) : ", matchObj.group(2)  
else:  
print "No match!!"





 运行结果:

matchObj.group() :  Cats are smarter than dogs
matchObj.group(1) :  Cats
matchObj.group(2) :  smarter
 
 
 
2. re.search(pattern, string, flags=0)


#!/usr/bin/python  
# -*- coding: UTF-8 -*-  
import re  
print(re.search('www', 'www.runoob.com').span())   # 在起始位置匹配 print(re.search('com', 'www.runoob.com').span())     # 不在起始位置匹配

运行结果:

(0, 3)
(11, 14)
 
 
3.re.search和re.match的区别

re.match只匹配字符串的开始,如果字符串开始不符合正则表达式,则匹配失败,函数返回None;而re.search匹配整个字符串,直到找到一个匹配。










  2.2 检索和替换
Python的re模块提供了re.sub用于替换字符串中的匹配项
re.sub(pattern, rep1, string, count=0, flags=0)





参考
【1】http://www.runoob.com/regexp/regexp-intro.html


没有评论:

发表评论

leetcode 17

17.   Letter Combinations of a Phone Number Medium Given a string containing digits from   2-9   inclusive, return all possible l...