Regular match-direct content substitution
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-dds = ‘替换日期格式: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‘
Case: Mobile phone number, phone number:, mobile phone number: ^1\d{10}\$ phone number required area code version: \d{3,4}-\d{8} \d{3}-\d{8}|\d{4}-\d{8} mailbox: E-mail authentication:/(\[email protected] (\w+.) +\w{2,3})?/Verify Email Address: ^ (\w+[-+.) \w+)
@\w+ ([-.] \w+). \w+ ([-.] \w+) *$ Verify email address:/[email protected]+. [a-z]+/xxx:xxx Number: ^ (\d{15}|\d{17} (\d|x)) \$
import reRE_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‘]
Python regex replace