python regex replace

來源:互聯網
上載者:User

標籤: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-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‘
案例:手機號碼,電話號:、手機號:^1\d{10}\$電話號碼必備區號版本:\d{3,4}-\d{8} \d{3}-\d{8}|\d{4}-\d{8}郵箱:電子郵件的驗證:/(\[email protected](\w+.)+\w{2,3})?/驗證Email地址: ^(\w+[-+.]\w+) @\w+([-.]\w+).\w+([-.]\w+)*$驗證Email地址: /[email protected]+.[a-z]+/×××:×××號碼: ^(\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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.