【python】python与正则 re的主要用到的方法列举,,【直接上代码】#co


【直接上代码】

#coding=utf-8
#1、先将正则表达式的字符串形式编译为Pattern实例

#2、使用Pattern实例处理文本并获得匹配结果

#3、最后使用Match实例获得消息,进行其他操作

import re

# 【1】 re.compile(string[,flag]) 将正则表达式编译成pattern对象

‘‘‘
# 【2】re.match(pattern,string[,flags])
# 从输入参数string的开头开始尝试匹配pattern,
# 遇到无法匹配的字符或者已经到达string末尾,立即返回None,反之获取匹配的结果

#将正则表达式编译成pattern对象
pattern = re.compile(r‘\d+‘)
#使用re.match匹配文本,获得匹配结果,无法匹配时将返回None
result1 = re.match(pattern,‘192abc‘)
if result1:
print result1.group()
else:
print ‘匹配失败1‘
result2 = re.match(pattern,‘abc192‘)
if result2:
print result2.group()
else:
print ‘匹配失败2‘
#输出结果--------> 192 匹配失败2 resul2匹配的时候遇到a的时候无法匹配,立即返回None
‘‘‘

‘‘‘
# 【3】re.search(pattern,string[,flags])
#match()函数只从string的开始位置匹配
#search()会扫描整个string查找匹配

#将正则表达式编译成pattern对象
pattern = re.compile(r‘\d+‘)
#使用re.search匹配文本获得匹配结果,无法匹配时将返回None
result1 = re.search(pattern,‘abc192def‘)
if result1:
print result1.group()
else:
print ‘匹配失败1‘
#运行结果--------> 192
‘‘‘

‘‘‘
# 【4】re.split(pattern,string[,maxsplit])
#按照能够匹配的子串将string分割后返回 列表
#maxsplit用于指定最大分割次数,不指定则将全部分割
pattern = re.compile(r‘\d+‘)
print re.split(pattern,‘A1B2C3D4‘)
#运行结果-----------> [‘A‘, ‘B‘, ‘C‘, ‘D‘, ‘‘]
‘‘‘

‘‘‘
# 【5】re.findall(pattern,string[,flags])
#搜索整个string,以列表形式返回能匹配的全部子串
pattern = re.compile(r‘\d+‘)
print re.findall(pattern,‘A1B2C3D4‘)
#运行结果----------> [‘1‘, ‘2‘, ‘3‘, ‘4‘]
‘‘‘

‘‘‘
# 【6】re.finditer(pattern,string[,flags])
#搜索整个string,以迭代器形式返回能匹配的全部Match对象
pattern = re.compile(r‘\d+‘)
matchiter = re.finditer(pattern,‘A1B2C3D4‘)
for match in matchiter:
print match.group()
#运行结果------>
# 1
# 2
# 3
# 4
‘‘‘

‘‘‘
# 【7】re.sub(pattern,repl,string[,count])
#使用repl替换string中每一个匹配的子串后返回替换后的字符串。
#当repl是一个字符串时,可以使用 \id 或 \g<id> 、 \g<name> 引用分组,但不能使用编号0.
#当repl是一个方法时,这个方法应当只接受一个参数(Match对象),并返回一个字符串用于替换(返回的字符串中不能再引用分组)
#count用于指定最多替换的次数,不指定时全部替换
p = re.compile(r‘(?P<word1>\w+) (?P<word2>\w+)‘) #使用名称引用
s = ‘i say ,hello world!‘
print p.sub(r‘\g<word2> \g<word1>‘,s)
p = re.compile(r‘(\w+) (\w+)‘) #使用编号
print p.sub(r‘\2 \1‘,s)
def func(m):
return m.group(1).title() + ‘ ‘ + m.group(2).title()
print p.sub(func,s)
#输出结果------>
# say i ,world hello!
# say i ,world hello!
# I Say ,Hello World!
‘‘‘


# 【8】re.subn(pattern,string[,count])
#返回 (sub(repl,string[,count]),替换次数)。
s = ‘i say ,hello world!‘
p = re.compile(r‘(\w+) (\w+)‘)
print p.subn(r‘\2 \1‘,s)
def func(m):
return m.group(1).title() + ‘ ‘ + m.group(2).title()
print p.subn(func,s)
#运行结果-------->
# (‘say i ,world hello!‘, 2)
# (‘I Say ,Hello World!‘, 2)

【python】python与正则 re的主要用到的方法列举

评论关闭