Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/324.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python:使用正则表达式删除某些内容_Python_Regex - Fatal编程技术网

Python:使用正则表达式删除某些内容

Python:使用正则表达式删除某些内容,python,regex,Python,Regex,我有一根像这样的绳子 ABC(a =2,b=3,c=5,d=5,e=Something) 我希望结果是这样的 ABC(a =2,b=3,c=5) 最好的方法是什么?我更喜欢在Python中使用正则表达式 抱歉,发生了更改,原始字符串更改为 ABC(a =2,b=3,c=5,dddd=5,eeee=Something) 当OP最终知道列表中有多少元素时,他还可以使用: shorter = re.sub(r',\s*d=[^)]+', '', longer) 它剪切、d=及其后的所有内容,但

我有一根像这样的绳子

ABC(a =2,b=3,c=5,d=5,e=Something)
我希望结果是这样的

ABC(a =2,b=3,c=5)
最好的方法是什么?我更喜欢在Python中使用正则表达式

抱歉,发生了更改,原始字符串更改为

ABC(a =2,b=3,c=5,dddd=5,eeee=Something)
当OP最终知道列表中有多少元素时,他还可以使用:

shorter = re.sub(r',\s*d=[^)]+', '', longer)
它剪切
、d=
及其后的所有内容,但不剪切右括号。

非正则表达式

import re  
re.sub(r',d=\d*,e=[^\)]*','', your_string)
>>> s="ABC(a =2,b=3,c=5,d=5,e=Something)"
>>> ','.join(s.split(",")[:-2])+")"
'ABC(a =2,b=3,c=5)'
如果你想让正则表达式去掉最后2个

>>> s="ABC(a =2,b=3,c=5,d=5,e=6,f=7,g=Something)"
>>> re.sub("(.*)(,.[^,]*,.[^,]*)\Z","\\1)",s)
'ABC(a =2,b=3,c=5,d=5,e=6)'

>>> s="ABC(a =2,b=3,c=5,d=5,e=Something)"
>>> re.sub("(.*)(,.[^,]*,.[^,]*)\Z","\\1)",s)
'ABC(a =2,b=3,c=5)'
如果总是前3个

>>> s="ABC(a =2,b=3,c=5,d=5,e=Something)"
>>> re.sub("([^,]+,[^,]+,[^,]+)(,.*)","\\1)",s)
'ABC(a =2,b=3,c=5)'

>>> s="ABC(q =2,z=3,d=5,d=5,e=Something)"
>>> re.sub("([^,]+,[^,]+,[^,]+)(,.*)","\\1)",s)
'ABC(q =2,z=3,d=5)'

抱歉,它们并不总是最后两个。@user483144:如果您有其他信息,请不要将其放在评论中,而是编辑您的问题。
>>> s="ABC(a =2,b=3,c=5,d=5,e=Something)"
>>> re.sub("([^,]+,[^,]+,[^,]+)(,.*)","\\1)",s)
'ABC(a =2,b=3,c=5)'

>>> s="ABC(q =2,z=3,d=5,d=5,e=Something)"
>>> re.sub("([^,]+,[^,]+,[^,]+)(,.*)","\\1)",s)
'ABC(q =2,z=3,d=5)'