本文由我司收集整编,推荐下载,如有疑问,请与我司联系
Python正则表达式练习
#re正则表达式import re#1通配符(.可匹配出换行符外的任意一个字符.ython-- qython +ython)#2\特殊字符进行转义Python\\或使用原始字符r’Python\’#3[]字符集[pg]ython-- 匹配python、gython [a-z]匹配a到z任意一个字符[a-zA-Z0-9]匹配任意一个大小写字母和数字#4 |选择符管道| python|jython-- 匹配字符串python和jython#5()子模式:只选择模式的一部分()p(ython|json)-- 匹配python pjson 单个字符#6? 可选项:在子模式后加?变成可选项”““r’()?(www\.)?python\’== 可能匹配的字符串:pythonpythonpythonpython”“““““(param)*:允许模式重复0次或多次(param)+:允许模式重复1次或多次(param){m,n}:允许模式重复m-n次
r’w*\.python\’== 匹配到’python’ 也会匹配’.python’,也会匹配’wwwwwpython’llo.....test.head.falj.kfal’print(re.split(‘[.]+’,txt))print(re.split(‘[.]’,txt))”““C:\python3.7\python.exe D:/Python-Test/qiubai/qiubai/Test9.pyNone _sre.SRE_Match object; span=(0, 1), match=‘p’ [‘He’, ‘hello’, ‘test’, ‘head’, ‘falj’, ‘kfal’][‘He’, ‘hello’, ‘‘, ‘‘, ‘‘, ‘‘, ‘test’, ‘head’, ‘falj’, ‘kfal’]”““#10 最多可以分割的部分数txt = ‘He.hello.....test.head.falj.kfal’print(re.split(‘[.]+’,txt,maxsplit=2))print(re.split(‘[.]+’,txt,m axsplit=1))”““C:\python3.7\python.exe D:/Python-Test/qiubai/qiubai/Test9.py[‘He’, ‘hello’, ‘test.head.falj.kfal’][‘He’, ‘hello.....test.head.falj.kfal’]”““#11在字符串中查找所有单词findall以列表的形式返回p = ‘[a-zA-Z]+’word = “hello,world,I,am you -- hefajlka?”print(“查找单词:”,re.findall(p,word))q = r’[-?]’print(“查找标点符号”,re.findall(q,word))”““C:\python3.7\python.exe D:/Python-Test/qiubai/qiubai/Test9.py 查找单词:[‘hello’, ‘world’, ‘I’, ‘am’, ‘you’, ‘hefajlka’]查找标点符号[‘-’, ‘-’, ‘?’]”““#12 sub 替换pat = ‘{name}’txt = “Hello {name}”print(re.sub(pat,’张三’,txt))”““C:\python3.7\python.exe D:/Python-Test/qiubai/qiubai/Test9.pyHello 张三”““#13 匹配对象和组’There (was a(wee) (cooper)) who (lived in fyfe)’”““组0 -- There was a wee cooper who lived in fyfe组1 -- was a wee cooper组2 -- wee组3 -- cooper组4 -- lived in fyfe”“““r’www\.(.+)\$== 组0包含整个字符串组1包含位于。