风-fmgao

导航

python re示例

#!/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 替换
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为了提高效率
pattern = re.compile('\w+@\w+\.(com|cn|edu)')
print(pattern.fullmatch('alex@oldboyedu.cn')) # <_sre.SRE_Match object; span=(0, 17), match='alex@oldboyedu.cn'>

# 计算器
s8 = '1-2*((60-30+(-40/5)*(9-2*5/3 + 7/3*99/4*2998 + 10*568/14)) - (-4*3)/(16-3*2))'

s81 = re.search('\([^()]+\)', s8)
print(s81) # <_sre.SRE_Match object; span=(12, 19), 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)']




posted on 2018-05-26 00:49  风-fmgao  阅读(581)  评论(0编辑  收藏  举报