Home > OS >  Split in Regex Python Infix Notation in Numerical Expressions
Split in Regex Python Infix Notation in Numerical Expressions

Time:12-26

I want to write a Python script where the user can input like that:

input1 = "12/(2 4)*21**2"
input2 = "12,/,(,2, ,4,),*,21,**,2"
input3 = "12 / ( 2   4 ) * 21 ** 2"

The output should always be such that:

output = ["12", "/", "(", "2", " ", "4", ")", "*", "21", "**", "2"]
  

What I have been doing is:

re.sub("([/ *](**))", r" \1 ", expression).split()

But it does not work and I am not super familiar with regex. Can anyone help out?

CodePudding user response:

How about using an alternation:

>>> re.findall(r"\d |\* |[- /()]", input1)
['12', '/', '(', '2', ' ', '4', ')', '*', '21', '**', '2']
>>> re.findall(r"\d |\* |[- /()]", input2)
['12', '/', '(', '2', ' ', '4', ')', '*', '21', '**', '2']
>>> re.findall(r"\d |\* |[- /()]", input3)
['12', '/', '(', '2', ' ', '4', ')', '*', '21', '**', '2']
  • Related