python正则表达式的简单使用
发布时间:2020-12-13 20:10:49 所属栏目:PHP教程 来源:网络整理
导读:模块函数 re.compile(pattern [,flag]) 把正则表达式预编译成正则表达式对象(模式对象),供以后使用. #模式对象,有re.compile()返回 pobj = re.compile( 'Hello,(.*)' ) pobj_sre.SRE_Pattern object at 0x7fb83dc9a530 re.match(pattern,string [,flag]) 如
模块函数re.compile(pattern [,flag])把正则表达式预编译成正则表达式对象(模式对象),供以后使用. #模式对象,有re.compile()返回
>>> pobj = re.compile('Hello,(.*)')
>>> pobj
<_sre.SRE_Pattern object at 0x7fb83dc9a530>
re.match(pattern,string [,flag])如果字符串起始处有0个或多个字符串匹配模式字符串,返回1个相应的匹配对象.否则返回None.同等于re.search的^pattern. >>> re.match('Hello,(.*)','Hello,you are welcome!')
<_sre.SRE_Match object at 0x7fb83db596c0> re.search(pattern,flag])扫描字符串string,返回匹配pattern模式的匹配对象(mobj),否则返回None. >>> re.search('(you are)',you are welcome!')
<_sre.SRE_Match object at 0x7fb83db59648> re.split(pattern,maxsplit=0])用指定模式分解字符,返回分解后的列表. >>> re.split('--','spam--egg--bar')
['spam','egg','bar'] re.sub(pattern,repl,string,count=0,flags=0)pattern模式替换string后的字符串由repl返回,repl可以是函数或字符串. >>> print re.sub(r'(.*)--(.*)--(.*)',r'I like 1 and 2,not 3','spam--egg--bar')
I like spam and egg,not bar 正则表达式对象(模式对象)模式对象是由re.compile()返回的对象,具有与re模块同构的函数. 如pobj.match(string [,flag]),pobj.search(string [,flag])等 匹配对象的方法mobj.group(n)返回n指定的匹配对象. mobj.groups()返回所有的匹配对象,用元组表示. 简单实例#coding=utf⑻
import re
string = 'Hello,you are welcome!'
#预编译成模式对象,由re.compile()返回
pobj = re.compile('Hello,(.*)')
#匹配对象,由match()返回mobj
mobj = pobj.match(string)
print mobj.group(1) #调用匹配对象的方法group()
#可以不生成模式对象,直接调用re模块函数,简写为
print re.match('Hello,you are welcome!').group(1) (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |