Useful Regex (python)

Useful regular expression I met during coding, will keep updating

Posted by CodingMrWang on July 23, 2018

This post is first created by CodingMrWang, 作者 @Zexian Wang ,please keep the original link if you want to repost it.

Regular expression

Some offical website:

A really good regex online matching website

Below, I will record some regular expressions that I think are useful.

  1. When you want to replace part of matching pattern

     import re
     a = 'aaabbccc'
     #replace the bb in the center to dd
     re.sub('(a+)bb(c+)', '\\1dd\\2', a)
    	
     #replace url in text
     dd = re.compile('(http|https):\/\/[a-zA-Z0-9.?\/&=:+.]*', re.S)
     dd.sub("", a)
    	
    
  2. ODD NUMBER AND ENVEN NUMBER OCCURANCE

     ^[^(A|B)]*((A|B)[^(A|B)]*(A|B)[^(A|B)]*)*[^(A|B)]*[^(C|D)]*([(C|D)[^(C|D)]*(C|D)[^(C|D)]*])*(C|D)[^(C|D)]*$
    
  3. Even number ac and even number bd

     Regex_Pattern = r"^((([ac]*[bd]){2})*[ac]*$)(([bd]*[ac]){2})*[bd]*$"
    
  4. When you want to find part of matching pattern

import re
a = 'aaabbccc'
#replace the bb in the center to dd
re.sub('(a+)bb(c+)', '\\1dd\\2', a)

#replace url in text
dd = re.compile('(http|https):\/\/[a-zA-Z0-9.?\/&=:+.]*', re.S)
dd.sub("", a)

#find Chinese tags in the content
#我给自己贴了 [TAG]游戏[TAG]、[TAG]音乐[TAG]、[TAG]看悲伤小说[TAG]、[TAG]电视都会流泪[TAG]、[TAG]嘻嘻就这么多了[TAG] 标签。
tags = re.findall('\[TAG\]([\x80-\xff]+)\[TAG\]', a) ​​​