tags:

views:

63

answers:

3

Hi,I've got a string looks 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)
+2  A: 
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.

eumiro
A: 
import re  
re.sub(r',d=\d*,e=[^\)]*','', your_string)
philippbosch
+2  A: 

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)'
ghostdog74