Python3 Re常用方法

常用的功能函数包括:compile、search、match、split、findall(finditer)、sub(subn)

1.compile
re.compile(pattern[, flags])
作用:把正则表达式语法转化成正则表达式对象

flags定义包括:
re.I:忽略大小写
re.L:表示特殊字符集 w, W, , B, s, S 依赖于当前环境
re.M:多行模式
re.S:' . '并且包括换行符在内的任意字符(注意:' . '不包括换行符)
re.U: 表示特殊字符集 w, W, , B, d, D, s, S 依赖于 Unicode 字符属性数据库

2.search
re.search(pattern, string[, flags])
作用:在字符串中查找匹配正则表达式模式的位置,返回 MatchObject 的实例,如果没有找到匹配的位置,则返回 None。

3.match
re.match(pattern, string[, flags])
match(string[, pos[, endpos]])
作用:match() 函数只在字符串的开始位置尝试匹配正则表达式,也就是只报告从位置 0 开始的匹配情况,
而 search() 函数是扫描整个字符串来查找匹配。如果想要搜索整个字符串来寻找匹配,应当用 search()。

例子:

import re
r1 = re.compile(r'world')  
if r1.match('helloworld'):
    print 'match succeeds'
else:
    print 'match fails'
if r1.search('helloworld'):
    print 'search succeeds'
else:
    print 'search fails'
###############################
#match fails
#search succeeds

4.split
re.split(pattern, string[, maxsplit=0, flags=0])
split(string[, maxsplit=0])
作用:可以将字符串匹配正则表达式的部分割开并返回一个列表

import re
inputStr = 'abc aa;bb,cc | dd(xx).xxx 12.12';
print(re.split(' ',inputStr))
#################################
#['abc', 'aa;bb,cc', '|', 'dd(xx).xxx', '12.12']

5.findall
re.findall(pattern, string[, flags])
findall(string[, pos[, endpos]])
作用:在字符串中找到正则表达式所匹配的所有子串,并组成一个列表返回
例:查找[]包括的内容(贪婪和非贪婪查找)

6.finditer
re.finditer(pattern, string[, flags])
finditer(string[, pos[, endpos]])
说明:和 findall 类似,在字符串中找到正则表达式所匹配的所有子串,并组成一个迭代器返回。

7.sub
re.sub(pattern, repl, string[, count, flags])
sub(repl, string[, count=0])
说明:在字符串 string 中找到匹配正则表达式 pattern 的所有子串,用另一个字符串 repl 进行替换。如果没有找到匹配 pattern 的串,则返回未被修改的 string。
Repl 既可以是字符串也可以是一个函数。

import re

def pythonReSubDemo():
    inputStr = "hello 123,my 234,world 345"
    
    def _add111(matched):
        intStr = int(matched.group("number"))
        _addValue = intStr + 111;
        _addValueStr = str(_addValue)
        return _addValueStr

    replaceStr = re.sub("(?P<number>d+)",_add111,inputStr,1)
    print("replaceStr=",replaceStr)

if __name__ == '__main__':
    pythonReSubDemo();
#########################################
#hello 234,my 234,world 345
原文地址:https://www.cnblogs.com/MR-FANWB/p/7988128.html