Python:正则表达式(三)-re模块的内容
来源:互联网 发布:网站关键词优化智搜宝 编辑:程序博客网 时间:2024/05/22 04:53
Python中re模块包含对正则表达式(regular expression)的支持,re模块包含一些常用的操作正则表达式的函数。接下来将通过Python代码实例来加深对这些函数的理解
re.compile(),re.search()和re.match()
re.compile()将以字符串书写的正则表达式转换为模式对象,可以实现更有效率的匹配。如果是在调用search或者match函数的时候使用的字符串表达的正则表达式,他们也会在内部将字符串转换为正则表达式对象。所以在使用compile完成一次转换之后,在每次使用模式的时候就不用再进行转换。
所以:re.search(pat,string)(pat是用字符串表示的正则表达式)等价于pat.search(string)(pat是用compile创建的模式对象)
#coding=utf-8'''@author=chengww3'''import reresult1 = re.search(r"(http://)?(www\.)?python\.org","http://www.python.org")print("%s" %result1)str = r"(http://)?(www\.)?python\.org"#定义包含正则的字符串pat = re.compile(str)#转为模式对象result2 = pat.search("http://www.python.org")print("%s" %result2)
match函数会在给定字符串的开头匹配正则表达式。因此,match(‘p’,’python’)返回真(即匹配对象MatchObject),而re.match(‘p’,’www.python.org’)则返回假(None)
#coding=utf-8'''@author=chengww3'''import reres1 = re.match('p','python')res2 = re.match('p','www.python.org')print(res1)print(res2)
如果要求模式匹配整个字符串,可以在模式的结尾加上美元符号。美元符号会对字符串的末尾进行匹配,从而顺延了整个匹配。我们对上述代码稍作修改。
#coding=utf-8'''@author=chengww3'''import reres1 = re.search('p','pythonp')res2 = re.search('p$','pythonp')print(res1)print(res2)
re.split()
函数re.split()会根据模式的匹配项来分隔字符串。它类似于字符串方法split,不过是用完整的正则表达式代替了固定的分隔符字符串。re.split允许任意长度的逗号和空格序列来分隔字符串。
#coding=utf-8'''@author=chengww3'''import restr = "alpha, beta,,,,gamma delta"#使用空格分隔res1 = re.split('[ ]+',str)print(res1)#使用逗号分隔res2 = re.split('[,]+',str)print(res2)#使用逗号和空格分隔res3 = re.split('[, ]+',str)print(res3)
maxsplit参数表示字符串最多可以分隔的次数,修改上述代码
#coding=utf-8'''@author=chengww3'''import restr = "alpha, beta,,,,gamma delta"#加入maxsplitres4 = re.split('[, ]+',str,maxsplit=2)print(res4)res5 = re.split('[, ]+',str,maxsplit=1)print(res5)
re.findall()
re.findall以列表形式返回给定模式的所有匹配项。比如要在字符串中查找所有的单词
#coding=utf-8'''@author=chengww3'''import repat = '[a-zA-Z]+'str = '"Hm... Err -- are you sure?" he said, sounding insecure.'res = re.findall(pat,str)print(res)
阅读全文
0 0
- Python:正则表达式(三)-re模块的内容
- Python 正则表达式 RE模块的使用方法
- Python的re模块学习---正则表达式
- 正则表达式和python的re模块
- re---Python的正则表达式模块
- Python 正则表达式 RE模块的使用方法
- Python re模块的正则表达式
- Python正则表达式re模块的使用方法
- PYTHON RE模块 正则表达式的使用
- Python re(正则表达式)模块
- Python 正则表达式(re模块)
- python中的re模块(正则表达式)
- python中的正则表达式(re模块)
- python re模块(正则表达式)
- python中的正则表达式(re模块)
- python正则表达式:re模块
- Python 正则表达式 re模块
- Python 正则表达式,re模块
- frontend 进化史
- JQuery+JQuery ui实现的弹出窗口
- DbUtils,一个替代JDBC的小工具类
- ZOJ 2136 Longest Ordered Subsequence(简单DP)
- java面试基础2
- Python:正则表达式(三)-re模块的内容
- js中生成json对象
- Day-01
- .net core 借助容联云实现短信验证码
- 51Nod-1832-先序遍历与后序遍历
- POJ1995 Raising Modulo Numbers(快速幂取模,模板题)
- 没有上司的舞会 树形DP 经典题目
- 一个错误
- 30. Substring with Concatenation of All Words