0

I have a query string that can look like this:

    ?blah=1&phoneNum=123-456-7890

OR

    ?phoneNum=123-456-7890

I'm using this regex: phoneNum=[^&]+&? to remove the substring phoneNum=__ from the query string, but it leaves a trailing & in the first case, which is no me gusta.

How do I adapt my regex pattern to optionally remove the preceeding &? so it removes both:

    phoneNum=123-456-7890

AND

    &phoneNum=123-456-7890

from the query string?

2
  • Could you tell us exactly what result you would like with the given inputs? Commented Feb 6, 2012 at 18:37
  • 1
    try using &?phoneNum=[^&]+&?... Although i am not sure WHY you are splitting your own query string instead of using a query string parser. Are you writing your own parser? What programming language are you using? Commented Feb 6, 2012 at 18:37

2 Answers 2

1

Just like the way you made the last & optional using ?, you can make the first one also optional:

&?phoneNum=[^&]+&?
Sign up to request clarification or add additional context in comments.

Comments

1

To strictly answer your question, you would prepend a &? to your regex, but I think it's a fragile approach, because the phoneNum param can potentially be anywhere in the query string: first, last or inbetween. If you ever start passing more parameters and you remove both & signs, you can end up with a messed up request.

I would parse the query, discard the phoneNumber parameter and construct the query again.

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.