标签:cooper
正则匹配-直接内容替换s = ‘dsoheoifsdfscoopaldshfowefcoopasdfjkl;‘
ss = s.replace(‘coop‘,‘###‘)
print(s,‘\n‘,ss)
dsoheoifsdfscoopaldshfowefcoopasdfjkl;
dsoheoifsdfs###aldshfowef###asdfjkl;
import re
regex = re.compile(r‘coop‘) # 正则匹配替换
regex.sub(‘$$$$$‘,‘sdlafhksdalkfcoopasdhflcoopa;sdhf‘)
‘sdlafhksdalkf$$$$$asdhfl$$$$$a;sdhf‘
# 通过分组替换字符串格式 ,mm/dd/yy -> yy-mm-dd
s = ‘替换日期格式:10/01/2008,12/25/2018‘
re_date = re.compile(r‘(\d+)/(\d+)/(\d+)‘)
re_date.sub(r‘\3-\1-\2‘,s) # 分组 1 2 3 分别对应上一行分组每个()的位置
‘替换日期格式:2008-10-01,2018-12-25‘
#########
# 替换字符串中多余的空格
s = ‘ coop regex python easy to learn,come on ‘
s.strip()
re_blank = re.compile(r‘\s+‘) # 匹配任意空吧字符,相当于[\t\n\r\f\v]
re_blank.sub(‘‘,s)
‘coopregexpythoneasytolearn,comeon‘
import re
RE_PHONE = re.compile(r‘\d{3,4}-\d{8} \d{3}-\d{8}|\d{4}-\d{8}‘)
def find_phone(text:str) -> list:
return RE_PHONE.findall(text)
def main():
text = ‘what ever number:110-11111111,0372-32122222‘
find_phone(text)
print(find_phone(text))
if __name__ == ‘__main__‘:
main()
[‘0372-32122222‘]
标签:cooper
原文地址:http://blog.51cto.com/13118411/2115788