You may use
[?&]sort_by=[^&]*$|(?<=[?&])sort_by=[^&]*&
to replace with an empty string. See the regex demo online.
It matches
[?&] - a ? or &
sort_by= - a literal substring
[^&]* - 0+ chars other than &
$ - end of string.
| - or
(?<=[?&]) - a location preceded with ? or &
sort_by= - a literal substring
[^&]* - 0+ chars other than &
& - a & char.
A Python demo:
key_to_remove = r'sort_by'
rx = r'[?&]{0}=[^&]*$|(?<=[?&]){0}=[^&]*&'.format(key_to_remove)
tests = ['?sort_by=name&role=user','?gender=male&sort_by=name_desc&role=user','?sort_by=name','?age=24&sort_by=fullname&gender=male','?age=24&sort_by=fullname']
for test in tests:
print(test + " => " + re.sub(rx, "", test))
Output:
?sort_by=name&role=user => ?role=user
?gender=male&sort_by=name_desc&role=user => ?gender=male&role=user
?sort_by=name =>
?age=24&sort_by=fullname&gender=male => ?age=24&gender=male
?age=24&sort_by=fullname => ?age=24
re.sub(r'\?sort_by=[^&]*$|(?<=[?&])sort_by=[^&]*&', '', get_params)?age=24&sort_by=fullname&gender=malethen the result is?age=24&&gender=maledouble & is comming . Is there any way to remove it .&optional. Usere.sub(r'\?sort_by=[^&]*$|(?<=[?&])sort_by=[^&]*&?', '', get_params). See this demo.