简体   繁体   中英

Split line by +-*/() (as delimeters) without omitting them in python

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.

re.split

infix = input("Enter the infix notation : ")
infix = re.split(r'([+-/*()])', infix)

Instead of splitting the string on delimiters, I recommend just searching for the tokens.

>>> re.findall(r'\d+|[-+/*()]', infix)
['(', '22', '+', '33', ')', '*', '44', '/', '300']
(?=\+|-|\/|\*|\(|\)|\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

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