正則表達式的使用方法主要有4種: re.search(進行正則匹配), re.match(從頭開始匹配) re.findall(找出所有符合條件的字符列表) re.split(根據條件進行切分) re.sub(根據條件進行替換)
匹配規則里的符號
# . 可以被當作任意字符, re.M 忽略開頭的換行符
res = re.match('^c.+\d', 'cheng123ronghua', flags=re.M) print(res)
# ^ 匹配當前字符串的開頭, ^c表示已c開頭,a$以a為結尾
res = re.search('^c[a-z]+a$', 'cdasda') print(res.group())
# $ 表示結尾
res = re.search('r[a-zA-Z]+a$', 'cheng321ronGHua123aronghua') print(res.group())
# * 表示匹配0個或者多個
print(re.findall('ab*', 'alexabbtomab')) # ['a', 'abb', 'ab']
# + 表示匹配一個或者多個
print(re.findall('x\d+a', 'alex123abc')) # ['x123a']
# ? 匹配0個或者一個
print(re.findall('宋惠喬?', '宋惠 宋惠喬')) # ['宋惠', '宋惠喬']
# {1,3} 匹配一個到三個之間
print(re.findall('[0-9]{1,3}', 'alex123alex1alex12')) # ['123', '1', '12']
# | 進行或操作的匹配,匹配其中一個即可
print(re.search('abc|ABC', 'abcABCCD').group()) # abc
# 將需要匹配的字母進行統一的保存
string = re.search('(abc){2}(\|\|=){2}', '123abcabc||=||=') print(string.group()) # abcabc||=||=
# \A 表示以什么開頭, 相當於上面的^
print(re.search('\Aa.+b\Z', 'a123b').group()) # a123b
# \Z 表示以什么結尾,相當於上面的$
print(re.search('b.+d\Z', '11b23d').group()) # b23d
# \D 匹配非數字
print(re.search('\D+', '123$-a').group()) # $-a
# \w 匹配數字或者字母
print(re.search('\w+o\w+', 'the old tsoms').group()) # tsoms
# \W 匹配非數字或者字母
print(re.search('\W+', 'abc123%-%-%abc').group()) # %-%-%
# \s 匹配空包字符 \n\r\t
print(re.findall('\s+', 'sd \r\n sd')) # [' \r\n ']
# (?P<>[]+) 進行分組構造字典
A = re.search('(?P<id>[0-9]+)(?P<name>[a-z]+)', '123alex') print(A.groupdict()) # {'id': '123', 'name': 'alex'}
# re.split() 進行數據切分
print(re.split('[ ]+', '123 123 12')) # ['123', '123', '12']
# re.sub 表示將數字進行替換|
print(re.sub('[0-9]+', '|', 'acv1dae2dasd3ads')) # acv|dae|dasd|ads
# 進行反斜杠匹配 r'\\'
print(re.split(r'\\', r'abc\123')) # ['abc', '123']
# re.I 忽略大小寫
print(re.search('[a-z]+', 'abcA', re.I).group()) # abcA
# re.M 忽略開頭的\n
print(re.search('^d123', '\nd123456', flags=re.M).group()) # d123
# re.S 匹配所有的字符串,包括換行符
print(re.findall(r'd.+s', 'd123\n\rs123', flags=re.S)) # ['d123\n\rs']
這里編寫了一個簡單的計算器
import re s = '1-2*((60-30 +(9-2*5/3+7/3*99/4*2998+10*568/14)*(-40 / 5))-(-4*3)/(16-3*2))' s = s.replace(' ', '') print(eval(s)) def get_grap(string): x = re.compile('\([^()]+\)').search(string) if x == None: return string else: return x.group() def cal(x): if '*' in x: return float(x.split('*')[0]) * float(x.split('*')[1]) else: return float(x.split('/')[0]) / float(x.split('/')[1]) def cal_sum(x): if '+' in x : return float(x.split('+')[0]) + float(x.split('+')[1]) elif '-' in x: return float(x.split('-')[0]) - float(x.split('-')[1]) def cal_grap(x): # 找出其中的乘和除 while True: y = re.compile('\d+(\.\d+)?[*/]-?\d+(\.\d+)?').search(x) if y == None: break y = y.group() x = x.replace(y, str(cal(y))) #找出其中的加減操作 while True: if re.search('[+][-]', x) != None: x = re.sub('[+][-]', '-', x) elif re.search('[-][-]', x) != None: x = re.sub('[-][-]', '+', x) y = re.compile('-?\d+(\.\d+)?[+\-]\d+(\.\d+)?').search(x) if y == None: break y = y.group() x = x.replace(y, str(cal_sum(y))) return x while True: if re.compile('\d+(\.\d+)?').search(s) != None: if re.compile('\d+(\.\d+)?').search(s).group() == s: break x = get_grap(s) if re.search('\(.+\)', x) != None: all = cal_grap(x)[1:-1] else: all = cal_grap(x) s = s.replace(x, all) print(s)