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.
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.
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)'
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
, eg like asdf_3 = "foo, bar"
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.