您的位置:首页 > 编程语言 > Python开发

python 正则表达式 python re模块的使用

2017-05-07 16:56 971 查看
正则表达式的用途和语法就不多说了,可以点击下面几个链接进行正则表达式的学习

1、菜鸟教程-正则表达式

2、正则表达式30分钟入门教程

接下来介绍 python 正则表达式的 re 模块  主要有6个函数 

一、re.match()      用正则表达式模式从字符串开头开始匹配    

二、re.search()    在字符串中查找表达式第一次出现

三、re.sub()     检索替换

四、re.split()     字符串分割  

五、re.findall(rule,target,[,flag])    在字符串中查找正则表达式模式的所有(非重复)出
现;返回一个匹配对象的列表    

flag:   re.M  多行模式     re.S  任意字符包括换行  

直接用代码演示各个函数的不同   注释的很仔细


# coding: utf-8

import re

def test():
#a=re.match('app','123app') #match() 用正则表达式模式从字符串开头开始匹配
#a=re.search('app','123app') #search()在字符串中查找表达式第一次出现

#bt='bit|bat|bet'
#a=re.match(bt,'He bit me') #无法匹配
#a=re.search(bt,'He bit me') #匹配的bit

#anyend='.end' (. 匹配任意单个字符 \n除外)
#a=re.match(anyend,'bend') #匹配bend
#a=re.match(anyend,'aaabend') #无法匹配
#a=re.match(anyend,'end') #无法匹配
#a=re.match(anyend,'benddsfsfsfsdf') #匹配bend
#a=re.search(anyend,'bend') #匹配bend
#a=re.search(anyend,'kkkkbendpppp') #匹配bend
#a=re.search(anyend,'end') #无法匹配
#a=re.search(anyend,'dasdsadend') #匹配bend

#a=re.match('[123][abc]','1c') #匹配
#a=re.match('[123][abc]','sss1c')
c54f
#无法匹配
#a=re.search('[123][abc]','sdfds1csdfads') #匹配1c

#a=re.match('\w\w\w-\d\d\d','aaa-123')

#b=re.match('(\w\w\w)-(\d\d\d)','aaa-123') #用括号括起来表示一个词组 可以用group() 传下标 取出来
#print b.group(1) #aaa
#print b.group(2) #123
#print b.group() #aaa-123

#从字符串的开头、结尾 、单词边界进行匹配
#a=re.match('^The','The end') #匹配 The
#a=re.match('^The','end. The') #无法匹配

#a=re.search('^The','The end') #匹配 The
#a=re.search('^The','end. The') #无法匹配

#(\b 匹配一个字边界,即字与空格间的位置 \B非字边界匹配)
#a=re.search(r'\bthe','bite the dog') #匹配 The
#a=re.search(r'\bthe','bitethe dog') #无法匹配
#a=re.search(r'\Bthe','bittethe dog') #匹配 the

#sub() 和 subn() 进行搜索和替换
#b=re.sub('X','你好','X欢迎来到技术小白的博客,X哈哈')
#print b #你好欢迎来到技术小白的博客,你好哈哈

#b=re.subn('X',u'你好',u'X欢迎来到技术小白的博客,X哈哈')
#print b #(u'\u4f60\u597d\u6b22\u8fce\u6765\u5230\u6280\u672f\u5c0f\u767d\u7684\u535a\u5ba2,\u4f60\u597d\u54c8\u54c8', 2)

#split() 字符串分割
#b=re.split('\s\s+',u'ni hao wo shi xiao bai good') #对两个以上的空格分割
#print b #[u'ni hao wo shi xiao bai', u'good']

html='<body>ni hao wo shi xiao bai </body>'
b=re.findall('<body>(.*?)</body>',html)
print ''.join(b) # 运行结果 ni hao wo shi xiao bai

a=None
if a==None:
print(u'无法匹配')
else:
print(a.group())

if __name__ == '__main__':
test()
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: