Search code examples
pythonregexlistsplitparentheses

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.


Solution

  • 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.