Search code examples
regexpython-3.6mathematical-expressions

Why are these regular expressions not working?


I want a regex to match complex mathematical expressions. However I will ask for an easier regex because it will be the simplest case.

Example input: 1+2+3+4

I want to separate each char: [('1', '+', '2', '+', '3', '+', '4')]

With a restriction: there has to be at least one operation (i.e. 1+2).

My regex: ([0-9]+)([+])([0-9]+)(([+])([0-9]+))* or (\d+)(\+)(\d+)((\+)(\d+))*

Output for re.findall('(\d+)(\+)(\d+)((\+)(\d+))*',"1+2+3+4") :

[('1', '+', '2', '+4', '+', '4')]

Why is this not working? Is Python the problem?


Solution

  • You could go the test route.
    See if its valid using re.match
    then just get the results with re.findall

    Python code

    import re
    
    input = "1+2+3+4";
    if re.match(r"^\d+\+\d+(?:\+\d+)*$", input) :
        print ("Matched")
        print (re.findall(r"\+|\d+", input))
    
    else :
        print ("Not valid")
    

    Output

    Matched
    ['1', '+', '2', '+', '3', '+', '4']