#!/usr/bin/env python
# Encoding:utf-8
# DATE:2018/5/25
Import re
s =' 124311200111155214 '
SS = Re.search (‘(? P<province>\d{3}) (? P<city>\d{3}) (? P<born_year>\d{4}) ', s). Groups ()
Print (ss)# (' 124 ', ' 311 ', ' 2001 ')
SS1 = Re.search (‘(? P<province>\d{3}) (? P<city>\d{3}) (? P<born_year>\d{4}) ', s)
Print (Ss1.groupdict ())# {' Province ': ' 124 ', ' City ': ' 311 ', ' Born_year ': ' 2001 '}
# split
S_SP =' Alex22jack23rain31jinxin50 '
S_SP1 = Re.split (' \d ', s_sp)
Print (S_SP1)# [' Alex ', ' ', ' Jack ', ', ' rain ', ' ', ' jinxin ', ', ']
S_SP2 = Re.split (' \d+ ', s_sp)
Print (S_SP2)#[' Alex ', ' Jack ', ' rain ', ' jinxin ', ']
S_SP3 = Re.findall (' \d+ ', s_sp)
Print (S_SP3)#[' 22 ', ' 23 ', ' 31 ', ' 50 ']
S3 =' Alex22jack23rain31jinxin50#mack-oldboy '
S31 = Re.split (' \d+|#|-', S3)
Print (S31)# [' Alex ', ' Jack ', ' rain ', ' jinxin ', ', ' Mack ', ' Oldboy ']
S4 =' Alex22jack23rain31jinxin50|mack-oldboy '
S41 = Re.split (' \d+|\| | -', S4)
Print (S41)# [' Alex ', ' Jack ', ' rain ', ' jinxin ', ', ' Mack ', ' Oldboy ']
S5 =' SSS\\123 '
S51 = Re.split (‘\\\\', S5)
Print (S51)# [' SSS ', ' 123 ']
# Sub Replacement
S6 =' Alex22jack23rain31jinxin50|mack-oldboy '
S61 = Re.sub (' \d+ ',' _ ', S6)
Print (S61)# Alex_jack_rain_jinxin_|mack-oldboy
S62 = Re.sub (' \d+ ',' _ ', S6,Count=2)
Print (S62)# Alex_jack_rain31jinxin50|mack-oldboy
S7 =' 9-2*5/3+7/3*99/4*2998+10*568/14 '
S71 = Re.split (' [-\*/+] ', S7)
Print (S71)# [' 9 ', ' 2 ', ' 5 ', ' 3 ', ' 7 ', ' 3 ', ' 99 ', ' 4 ', ' 2998 ', ' 10 ', ' 568 ', ' 14 ']
S72 = Re.split (' [-\*/+] ', S7,maxsplit=2)
Print (S72)# [' 9 ', ' 2 ', ' 5/3+7/3*99/4*2998+10*568/14 ']
# Fullmatch compile compile to improve efficiency
Pattern = Re.compile (' \[email protected]\w+\. (com|cn|edu) ')
Print (Pattern.fullmatch (' [email protected] ')# <_sre. Sre_match object; span= (0, +), match= ' [email protected] ' >
# Calculator
S8 = 1-2* (60-30+ ( -40/5) * (9-2*5/3 + 7/3*99/4*2998 + 10*568/14)-( -4*3) /(16-3*2)) '
print (s81) # <_sre. Sre_match object; span=, Match= ' ( -40/5),
s82 = Re.findall ( "\ ([^ ()]+\) ', S8)
print (s82) # [' ( -40/5) ', ' (9-2*5/3 + 7/3*99/4*2998 + 10*568/14) ', ' ( -4*3) ', ' (16-3*2) ']
Span style= "color: #808080; Font-style:italic ">
Python re example