Regular expression for simple math expressions

后端 未结 4 1450
不思量自难忘°
不思量自难忘° 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:03

    Simply try this.

    import re
    q = '23 * 345 - 123+65'
    regexparse = r'(\d+)|[-+*/]'
    for i in re.finditer(regexparse, q):
        print i.group(0)
    

    output:

    23
    *
    345
    -
    123
    +
    65
    

提交回复
热议问题