import re
"""
(^开头)($结尾)(.除换行任意)(\w数字字母下划线)(\d数字)(*0或多个)(+1或多个)(?0或一个,非贪婪)
([^]不包含中括号内的内容)
"""
#找
origin = "hello tomx tjjmx kk 459"#origin起点
r = re.match("(?P<n1>H)(?P<n2>\w+)",origin,re.I|re.S)#从头匹配,?P<key>是groupdict里的key
# flags=re.I是忽略大小写,S是使.匹配包括换行符在内的所有字符,M多行匹配,影响 ^ 和 $
print(r.group(),r.groups(),r.groupdict())#hello ('h', 'ello') {'n1': 'h', 'n2': 'ello'}
#简单,分组
r2 = re.search("t(\w+).*(?P<n1>\d)$",origin)#浏览全部字符串,匹配第一个符合规则的字符串
print(r2.group(),r2.groups(),r2.groupdict())#tomx tjjmx kk 459 ('omx', '9') {'n1': '9'}
# re.findall()#匹配到的所有东西全部放到一个列表中
r3 = re.findall("(t)((\w+)(m))(x)",origin)#()从左到右,从外到内
print(r3)#[('t', 'om', 'o', 'm', 'x'), ('t', 'jjm', 'jj', 'm', 'x')]
# re.finditer()#可迭代的
r4 = re.finditer("(t)((\w+)(m))(?P<n1>x)",origin)
print(r4)
for i in r4:
print(i.group(),i.groups(),i.groupdict())#tomx ('t', 'om', 'o', 'm', 'x') {'n1': 'x'}
# re.split()分割
r5 = re.split("t\w+",origin,1)#1为只分割一次
print(r5)#['hello ', ' tjjmx kk 459']
jisuanqi = "1+(2*(3*4+5)*(4+7)+4)*7"
print(eval(jisuanqi))#直接计算出结果
# 计算器
def f1(xx):
result = eval(xx)
print(result)
return result
while True:
print(jisuanqi)
r6 = re.split("\(([^()]+)\)",jisuanqi,1)#分割最小(),取第一个
if len(r6) == 3:
# before = r6[0]
# content = r6[1]
# after = r6[2]
before,content,after = r6
r = f1(content)
new_str = before+str(r)+after
jisuanqi =new_str
else:
print(f1(jisuanqi))
break
# re.sub()替换
origin2 = "as4jdkh555jkgh4hhhf45sdfhgg45hhhhh"
new_str2 = re.sub("\d+","zzz",origin2)
print(new_str2)#aszzzjdkhzzzjkghzzzhhhfzzzsdfhggzzzhhhhh
a,b = re.subn("\d+","zzz",origin2)
print(a,b)