Python regex replace

Source: Internet
Author: User
Tags regex replace

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.