简体   繁体   中英

How do I split values in a list by parenthesis using regex in Python?

What I mean by split by value, assume a list has 1 string value: mylist = ["3+4(5-3)-(9+4)"]

I want to split the values so they are separate string values like: mylist = ["3+4", "(", 5-3", ")", "-", "(", "9-4", ")"]

So far, the below code I attached does the same thing, but splits it between operators so if I input ["3+3"] , it will output

mylist = ["3", "+", "3"]

import re
mylist = input("Equation: ")
mylist = re.compile("(?<=\d)([- + / *])(?=\d)").split(mylist)

I'm just trying to make it so that it does the same thing with parenthesis because adding a parenthesis in the parameters mess with the regex syntax.

Try this:

>>> import re
>>> r = re.compile("([()])")
>>> r.split("abc(def(ghi)jkl")
['abc', '(', 'def', '(', 'ghi', ')', 'jkl']
>>> 

The outer parentheses in the regex cause the separators to be retained as elements of the split list.

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