正则表达式分割运算的技巧

 

1. 分割后用长度判断是否存在'+-*/'类似的运算符!

1  if len(res_as.group().split('+')) > 1   # 分割后用长度判断是否存在'+-*/'类似的运算符!

 

2.可以替代如下判定写法:

1 sym = re.search('[\*\/]{1}',res_1).group()
2 
3 a,b = re.split('[\*\/]{1}',res_1)
4 
5 if sym == '*':

 

3.  重新组织新的字符串的写法!

1 new_md = '%s%s%s'%(front,resmd, rear)

 

4. 可以指定分割次数!

1  re.split(r'\(([^()]+)\)', formula, 1)   

 

4. 注意:使用带括号和不带括号分割是不同效果的

1 print(re.split('2-1',a))      # ['3-1+(', ')+3']
2 print(re.split('(2-1)',a))    # ['3-1+(', '2-1', ')+3']
3 print(re.split('\(([^()]+)\)',a))   #['3-1+', '2-1', '+3']

 



 

posted @ 2017-11-25 22:04  子夜星云  阅读(3844)  评论(0)    收藏  举报