Regular expression for simple math expressions

后端 未结 4 1456
不思量自难忘°
不思量自难忘° 2021-01-21 23:40

As an exercise I was trying to come up with a regex to evaluate simple algebra like

q = \'23 * 345 - 123+65\'

From here I want to get \'23\', \

4条回答
  •  耶瑟儿~
    2021-01-22 00:12

    Your regex is confusing. Better to use re.split() for this purpose:

    q = '23 * 345 - 123+65'
    print re.split('\s*([-+/*])\s*', q)
    

    Outputs:

    ['23', '*', '345', '-', '123', '+', '65']
    

提交回复
热议问题