Skip to content Skip to sidebar Skip to footer

Python: Use Regular Expression To Remove Something

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 express

Solution 1:

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.

Solution 2:

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

Solution 3:

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

Post a Comment for "Python: Use Regular Expression To Remove Something"