1

I want to remove some querystring attribute from my url, I tried some regex but didn't get the exact solution for this. Please help me to out of it. eg:

String qString = "category=Popular&code=14290115";
qString = qString .replaceAll("(?<=[?&;])code=.*?($|[&;])",""); 
output: category=Popular&

the above regex is removing the attribute but not removing & symbol. So please suggest me for this.

8
  • no... I just want to remove only case parameter. I want this: http://www.domain.com?id=1&start=2&end=5 Commented Mar 24, 2014 at 7:43
  • 1
    what is the problem? It works fine. See Demo here Commented Mar 24, 2014 at 7:46
  • 2
    Why don't you just split into query elements, build a list from the array without the element you want and reconstruct the query string? Commented Mar 24, 2014 at 7:49
  • there is a problem only when case is the last parameter. So maybe, after the replacement, you can test if qString ends with '&' and remove it. Commented Mar 24, 2014 at 7:49
  • Oh Sorry... I edited my question. I am using this id=1&case=edit&start=2&end=5 as query string Commented Mar 24, 2014 at 7:51

1 Answer 1

4

Don't use a regex for this. It's an utter nightmare because any character could be percent-encoded, e.g. ?foo=bar is exactly the same as ?%66oo=%62ar. Parse the URL, then the query string, then rebuild it. Take a look at URIBuilder and URLEncodedUtils out of the Apache Commons HTTP Client.

Sign up to request clarification or add additional context in comments.

2 Comments

Ok Thanks for your suggestion @David, I need to try and check.
I am using URIBuilder and its really helpful. Thanks @David

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.