[英]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)"]
我的意思是按值拆分,假设列表有 1 个字符串值:
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", ")"]
我想拆分这些值,使它们成为单独的字符串值,例如:
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到目前为止,我附加的以下代码执行相同的操作,但将其拆分为运算符,因此如果我输入
["3+3"]
,它将输出
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.正则表达式中的外括号导致分隔符被保留为拆分列表的元素。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.