正则表达式的使用

正则表达式深层次的用法:

import re

match=re.match(r'(\w+)(\w+)(?P<sign>.*)','hello world!')

print match.string#匹配时使用的文本

print match.re #匹配时使用的pattern对象

print match.pos #匹配时正则表达式开始的索引位置

print match.endpos #正则表达式是结束搜素的索引

print match.lastindex #最后一个被捕获的分组在文本中的索引

print match.lastgroup #最后一个被捕获分组的别名

for group in match.groups():

print group

print match.groupdict("sign")#通过分组的别名获得匹配的字符串

print match.start(2)#通过指定分组中的索引来获取匹配字符串在文本中的起始位置

print match.end(1)# 作用与上面的差不多

print match.span(1) #这个就是返回匹配字符串在文本中的起始和结束的位置

print match.expand(r'\1')


#search方法与match方法极其类似,区别在于match()函数只检测re是不是在string的开始位置匹配,search()会扫描整个string查找匹配,match()只有在0位置匹配成功的话才有返回,如果不是开始位置匹配成功的话,match()就返回None。同样,search方法的返回对象同样match()返回对象的方法和属性。


match=re.match(r'world','hello world')#返回一个match对象

print match

match=re.search(r'world','hello world')#返回一个match对象


if match:

print match.group()


#按照能够匹配的子串将string分割后返回列表。maxsplit用于指定最大分割次数,不指定将全部分割

pattern=re.compile(r"\d+")

split=re.split(pattern,"one1two2three3four4",3) #可以设定最大分割次数

print split


#搜索string,以列表形式返回全部能匹配的子串

pattern=re.compile(r"\d+")

print re.findall(pattern,"one1two2three3four4")

#re.finditer() 返回一个列表迭代器


#使用repl替换string中每一个匹配的子串后返回替换后的字符串。

#当repl是一个字符串时,可以使用\id或\g、\g引用分组,但不能使用编号0。

#当repl是一个方法时,这个方法应当只接受一个参数(Match对象),并返回一个字符串用于替换(返回的字符串中不能再引用分组)。

#count用于指定最多替换次数,不指定时全部替换。


pattern=re.compile(r"(\w+) (\w+)")

string="i say, hello world"

sub=re.sub(pattern,r"\2 \1",string)

def function(match):

return match.group(1).title()+" "+match.group(2).title()

print sub

print re.sub(pattern,function,string,1)


#re.subn(),返回(sub(repl, string[, count]), 替换次数)


#.Python Re模块的另一种使用方式,,可以通过pattern.match,pattern.search调用

print pattern.sub(function,string,1)



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值