tags:

views:

41

answers:

3

In python, I've got a string like

ABC(a =2,bc=2, asdf_3 = None)

By using regular expression, I want to make it like

ABC(a =2,bc=2)

I want to remove the parameter that named 'asdf_3', that's it!

Update: The parameters can be a lot, only the asdf_3 is same in all cases, the order is usually the last one.

A: 
import re

foo = 'ABC(a =2,bc=2, asdf_3 = None)'
bar = re.sub(r',?\s+asdf_3\s+=\s+[^,)]+', '', foo)

# bar is now 'ABC(a =2,bc=2,)'

The \s+ portions let you match any amount of whitespace, and the [^,)]+ part lets it basically anything on the right-hand side that doesn't start another argument.

Amber
I need to get rid of the common after bar=2 as well.
That's what the `,?` at the beginning of the pattern is for.
Amber
A: 

you are doing homework right? Show some effort on your part next time, since you already asked such questions like this

>>> foo.split("asdf_3")[0].strip(", ")+")"
'ABC(a =2,bc=2)'

>>> re.sub(",*\s+asdf_3.*",")",foo)
'ABC(a =2,bc=2)'
ghostdog74
A: 

Since you say that the asdf_3 parameter is only usually the last one, I suggest the following:

result = re.sub(
    r"""(?x) # verbose regex
    ,?       # match a comma, if present
    \s*      # match spaces, if present
    asdf_3   # match asdf_3
    [^,)]*   # match any number of characters except ) or ,
    """, "", subject)

This assumes that commas can't be part of the argument after asdf_3, e. g. like asdf_3 = "foo, bar".

Tim Pietzcker