2

I want to replace querystring value but it's creating some problems:

Problem 1: Its Removing the "&" symbol after replacing

String queryString = "?pid=1&name=Dell&cid=25";
String nQueryString=queryString.replaceAll("(?<=[?&;])pid=.*?($|[&;])","pid=23");
System.out.println(nQueryString);          

output of above example ?pid=23name=Dell&cid=25

you can see its removed the "&" after pid

Problem 2: Its not working if I removed the "?" symbol from the queryString variable.

String queryString = "pid=1&name=Dell&cid=25";
String nQueryString=queryString.replaceAll("(?<=[?&;])pid=.*?($|[&;])","pid=23");
System.out.println(nQueryString);          

output of above example ?pid=1&name=Dell&cid=25

We can say the regex is not working, So anyone can suggest me better regex which completely fulfill my requirements.

2 Answers 2

1
queryString.replaceAll("(?<=[?&;])pid=.*?(?=[&;])", "pid=23")

Difference is that I'm using a positive-lookahead: (?=[&;]), which is zero-length, making it atomic, and is not actually included in the replacement via replaceAll(), just like your original positive-lookbehind is not replaced.

Alternatively, we can match until a & or ; is found, but not included in the replacement, ie:

queryString.replaceAll("(?<=[?&;])pid=[^&;]*", "pid=23")

[^&;] : ^ negates the following: &;, so [^&;]* will match until a ; or & is encountered.

Yours does not work because ($|[&;]) is a non-atomic group, specifically a capturing group, and thus is included in the replacement. NB: a non-capturing group (?:$|[&;]) would also fail here.

To your final note, you're using a positive look-behind for ?, &, and ;, so by removing the ?, it will no longer match, which makes sense.

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

2 Comments

Yes @Steve you are right, but when I was trying to replace the same queryString with blank space then its not removing "&" symbol. queryString.replaceAll("(?<=[?&;])pid=[^&]*","") will give ?&name=Dell&cid=25
Oh yes, I just wanted to replace the queryString values, but I just tried to replace the attribute. I would be better if the same regex will work for me, that's why I tried and commented. Thanks @Steve, your answer is very useful for me.
0

Use this regex instead:

String nQueryString = queryString.replaceAll("(?<=[?&;])pid=[^&]*", "pid=23");
//=> ?pid=23&name=Dell&cid=25

Here [^&]* is called negation matching pattern, that will match query string value until & is found OR else end of string is found thus leaving rest of the query string un-effected.

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.