简体   繁体   中英

Split in Regex Python Infix Notation in Numerical Expressions

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?

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']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM