使用正则表达式分别捕获“(3 + 44)* 5 / 7”中的所有运算符、括号和数字

Capturing all operators, parentheses and numbers separately in "(3 + 44)* 5 / 7" with Regex

对于输入字符串:st = "(3 + 44)* 5 / 7"

我希望仅使用正则表达式获得以下结果:["(", "3", "+", "44", ")", "*", "5", "/", "7"]

尝试次数:

  1. >>> re.findall("[()\d+\-*/].?", st)
    ['(3', '+ ', '44', ')*', '5 ', '/ ', '7']
    

    但我还需要分别捕获 '(3'')*' 中的括号。

  2. >>> re.findall("[()\d+\-*/]?", st)    
    ['(', '3', '', '+', '', '4', '4', ')', '*', '', '5', '', '/', '', '7', '']
    

    这会产生大量空白标记。

您不能在字符 class 中使用 \d+ 等多字符结构。

所以你可以像这样通过蛮力来做到这一点:

re.findall(r"\(|\)|\d+|-|\*|/", st)

或者您可以使用字符 class 作为单字符标记,与其他字符交替使用:

re.findall(r"[()\-*/]|\d+", st)