[Toc] >[success] # 闭包 ~~~ 1. 查具体原理 ~~~ >[danger] ##### 案例匹配大小写 ~~~ import re text = "UPPER PYTHON,lower python, Mixed Python" def mathcase(word): def replace(m): text = m.group() if text.isupper(): return word.upper() elif text.islower(): return word.lower() elif text[0].isupper(): return word.capitalize() else: return word return replace re.sub('python',mathcase('snake'),text,flags=re.IGNORECASE) 打印结果 UPPER SNAKE,lower snake, Mixed Snake ~~~ >[danger] ##### 匹配换行 * 如果未使用,换行匹配出现的结果 ~~~ import re text = """ aaaatest/* UPPER PYTHON, lower python, Mixed Python*/ """ a = re.findall(r"/\*(.*?)\*/", text,) print(a) 打印结果: [] ~~~ * 使用非捕获组,捕获异常 ~~~ 其实匹配的方法就是,告诉两种匹配开始,其中一种是从\n 开始匹配 ~~~ ~~~ import re text = """ aaaatest/* UPPER PYTHON, lower python, Mixed Python*/ """ a = re.findall(r"/\*((?:.|\n)*?)\*/", text,) print(a) 打印结果: [' UPPER PYTHON,\n lower python, Mixed Python'] ~~~ * 使用正则自带DOTALL ~~~ import re text = """ aaaatest/* UPPER PYTHON, lower python, Mixed Python*/ """ a = re.findall(r"/\*(.*?)\*/", text,re.DOTALL) print(a) 打印结果: [' UPPER PYTHON,\n lower python, Mixed Python'] ~~~