Reputation: 43
Good day.
I'm trying to split (tokenize) a string like
(22+33)* 44 / 300
and get output like
['(','22','+','33',')','*','44','/','300']
so far I tried to use
infix = input("Enter the infix notation : ")
infix = re.split(r'[+-/*()]', infix)
but it omits delimiters and creates '' elements at list.
Upvotes: 1
Views: 101
Reputation: 361919
Instead of splitting the string on delimiters, I recommend just searching for the tokens.
>>> re.findall(r'\d+|[-+/*()]', infix)
['(', '22', '+', '33', ')', '*', '44', '/', '300']
Upvotes: 3
Reputation: 67988
(?=\+|-|\/|\*|\(|\)|\b\d+\b)
Try this.
use y= re.sub(r"(?=\+|-|\/|\*|\(|\)|\b\d+\b)","\n",x)
print y.split("\n")
.
See demo.
http://regex101.com/r/kK4cB5/1
Upvotes: 0