正则表达式中[\b],\b,\B的用法:
发布时间:2020-12-14 05:35:50 所属栏目:百科 来源:网络整理
导读:re模块中flags: 1.re.IIgnorecase 忽略大小写2.re.LLocala-aware本地化识别匹配3.re.MMultiline 多行匹配,"^"与"$"匹配行首与行尾,会增加换行符之前和之后.4.re.Sdotall 使"."特殊字符完全匹配任何字符,包括换行;没有这个标志,"."匹配除了换行符外的任何字符
re模块中flags:1.re.I Ignorecase 忽略大小写 2.re.L Locala-aware本地化识别匹配 3.re.M Multiline 多行匹配,"^"与"$"匹配行首与行尾,会增加换行符之前和之后. 4.re.S dotall 使"."特殊字符完全匹配任何字符,包括换行;没有这个标志,"."匹配除了换行符外的任何字符 5.re.X verbose 当该标志被指定时,在 RE 字符串中的空白符被忽略,除非该空白符在字符类中或在反斜杠之后。 它也可以允许你将注释写入 RE,这些注释会被引擎忽略; 注释用 “#”号 来标识,不过该符号不能在字符串或反斜杠之后。 示例: import re #关于flags的设置 #1.忽略大小写 text = 'PYTHON python' p1 = 'p' print('忽略大小写:',re.findall(p1,text,flags=re.I)) #2.多行模式 text = '我爱数学n我爱Pythonn我爱python' pat1 = '^我' r1 = re.findall(pattern=pat1,string=text) r2 = re.findall(pattern=pat1,string=text,flags=re.M) print('非多行匹配:',r1) print(' 多行匹配:',r2) #匹配任何字符: text = ''' 我爱Python 我爱pandas ''' pat1 = '.我' # search r1 = re.findall(pattern=pat1,flags=re.S) print('包括换行符:',r1) r2 = re.findall(pattern=pat1,string=text) print('不带换行符:',r2) ########################## 忽略大小写: ['P','p'] 非多行匹配: ['我'] 多行匹配: ['我','我','我'] 包括换行符: ['n我','n我'] 不带换行符: [] re模块中sub用法:? 用于替换字符串中的匹配项
re.compile:? compile函数用于编译正则表达式,生成一个正则表达式(pattern)对象,和findall,match与search函数使用.
import re def main(): content = 'Hello,I am Jerry,from Chongqing,a montain city,nice to meet you……' regex = re.compile('w*ow*') x = regex.findall(content) print(x) if __name__ == '__main__': main() # ['Hello','from','Chongqing','montain','to','you'] 正则表达式关于[b],b,B的区别:
print(re.sub(re.compile(r"[b]",re.S),"|","That bdang-to_ot_in' b#[email?protected]b#$ varbmint's cost me $199.95!")) ########################## That |dang-to_ot_in' |#[email?protected]|#$ var|mint's cost me $199.95!
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |