开发者

Python: Use Regular expression to remove something

I've got a string looks 开发者_JAVA百科like this

ABC(a =2,b=3,c=5,d=5,e=Something)

I want the result to be like

ABC(a =2,b=3,c=5)

What's the best way to do this? I prefer to use regular expression in Python.

Sorry, something changed, the raw string changed to

ABC(a =2,b=3,c=5,dddd=5,eeee=Something)


longer = "ABC(a =2,b=3,c=5,d=5,e=Something)"

shorter = re.sub(r',\s*d=\d+,\s*e=[^)]+', '', longer)

# shorter: 'ABC(a =2,b=3,c=5)'

When the OP finally knows how many elements are there in the list, he can also use:

shorter = re.sub(r',\s*d=[^)]+', '', longer)

it cuts the , d= and everything after it, but not the right parenthesis.


Non regex

>>> s="ABC(a =2,b=3,c=5,d=5,e=Something)"
>>> ','.join(s.split(",")[:-2])+")"
'ABC(a =2,b=3,c=5)'

If you want regex to get rid always the last 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)'

If its always the first 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)'


import re  
re.sub(r',d=\d*,e=[^\)]*','', your_string)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜