1

i want to remove all sort_by=<string> from the variable get_params.

the get_params will be either ?sort_by=name&role=user or ?gender=male&sort_by=name_desc&role=user or '?sort_by=name'

and i want something output like this

i tried this

re.sub("^sort_by=&*$",r'', get_params)

but its not working .

i looked into many answers in stackoverflow but i couldnt do it

5
  • Try re.sub(r'\?sort_by=[^&]*$|(?<=[?&])sort_by=[^&]*&', '', get_params) Commented Oct 25, 2018 at 14:23
  • @WiktorStribiżew thanks for helping me. if the variable is ?age=24&sort_by=fullname&gender=male then the result is ?age=24&&gender=male double & is comming . Is there any way to remove it . Commented Oct 25, 2018 at 14:26
  • My comment has been updated. Actually, I see I need to make last & optional. Use re.sub(r'\?sort_by=[^&]*$|(?<=[?&])sort_by=[^&]*&?', '', get_params). See this demo. Commented Oct 25, 2018 at 14:28
  • i really apprectiate your help ...thanks a loot... if you dont mind could you please explain a bit about this regex .. Commented Oct 25, 2018 at 14:56
  • sorry @WiktorStribiżew i got it from the demo link.. thanks a lot..... Commented Oct 25, 2018 at 15:04

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.