Dev.K.
Dev.K.

Reputation: 2488

Python RegEx Remove / Replace

I have a string like this:

param1=1234&param2=abcd&param3=efgh&param4=ijkl

I want to remove any parameter from the string above, User will enter parameter name like

param1,param2 etc.

And depending on that, the entire parameter and its value should be removed from the above string.

For example if user wants to remove param3, the result string should look like

param1=1234&param2=abcd&param4=ijkl

Thanks in Advance,

Upvotes: 0

Views: 73

Answers (3)

kqr
kqr

Reputation: 15028

Does something like this work?

>>> import re
>>> def removeparam(query, name):
...     return re.sub(name + r'=[^&]*(&|$)', '', query).rstrip('&')
...
>>> removeparam('param1=1234&param2=abcd&param3=efgh&param4=ijkl', 'param3')
'param1=1234&param2=abcd&param4=ijkl'

I have tested it for both the first and the last parameter, and it seems to behave well with both, as opposed to some of the other proposed solutions.


If you want to remove several parameters at once, put them in a list, and you can do the following:

>>> import functools
>>> unwanted = ['param4', 'param1', 'param3']
>>> functools.reduce(removeparam, unwanted,
...     'param1=1234&param2=abcd&param3=efgh&param4=ijkl')
...
'param2=abcd'

You are left with the only parameter not being removed!

Upvotes: 0

georg
georg

Reputation: 215009

>>> import re
>>> qs = "param1=1234&param2=abcd&param3=efgh&param4=ijkl"
>>> name = "param2"
>>> rx = '(^|&)' + name + '=[^&]*'
>>> re.sub(rx, '', qs)
'param1=1234&param3=efgh&param4=ijkl'

It might be better though to use dedicated functions when working with query strings:

>>> import urllib, urlparse
>>> qs = "param1=1234&param2=abcd&param3=efgh&param4=ijkl"
>>> qry = urlparse.parse_qs(qs)
>>> del qry['param2']
>>> urllib.urlencode(qry, True)
'param4=ijkl&param3=efgh&param1=1234'

Upvotes: 2

Ofir Israel
Ofir Israel

Reputation: 3913

Use re.sub():

import re

>>> qs = "param1=1234&param2=abcd&param3=efgh&param4=ijkl"
>>> omit = "param3"
>>> re.sub(r'%s=[^&]+&'%omit,'',qs)
'param1=1234&param2=abcd&param4=ijkl'

Upvotes: 0

Related Questions