Python---re

来源:互联网 发布:青岛知行国际是真的吗 编辑:程序博客网 时间:2024/04/28 10:55
'''help----re'''import restring1='100 NORTH BROAD MAIN ROAD. 100'print(string1.replace('ROAD.', 'RD.'))print(re.sub('ROAD$', 'RD.', string1))print(re.sub('^100', '200', string1))'''$ means endwith, ^ means startwith\\b means complete wordr means don't translate for \'''string2='100 ROAD BROAD.'print(re.sub('\\bROAD', 'RD.', string2))print(re.sub(r'\bROAD', 'RD.', string2))print(re.sub(r'\bROAD', 'RD.', string2))string3 ='Monday is My  day M'print(re.search('^M?M?M', string3))string5='MM'print(re.search('^M?M?$', string5))'''^ and $ means no symbol is before than M and no symbol is after M, it is critical'''string4='LonDay is'print(re.search('(^M|^L)?i?(s|k)', string4))'''can not use ^(M|L)'''print(re.search('^M{0,3}$', 'MMM'))pattern1='''^#it means start with MM#the first pattern character{0,3}#the scope ,min is 0 ,max is 3$#then end of pattern, end with M'''print(re.search(pattern1, 'MMM', re.VERBOSE))pattern2=re.compile(r'(\d{3})')print(pattern2.search('422').groups())'''pay attention: can not miss () of (\d{3})'''pattern3=re.compile(r'^(\d{3})-(\d{3})-(\d*)-(\d+)-(\D+)$')print(pattern3.search('301-555--122-s').groups())'''* means 0 or more, + means 1 or more, D means not decimal ,d means decimal'''print(re.sub('$', 'es', 'box'))print(re.sub('[abc]','A', 'america'))'''[] means select one of them, sub() means replace'''print(re.sub('[^abc]', 'A', 'america'))'''^ in [] means , except'''print(re.findall('[0-9]', '1 is my favorite number from 0 to 100'))

0 0
原创粉丝点击