user11230
user11230

Reputation: 549

How to substitute a query parameter in a string url

Hello I have a url string like

http://example.com/foo/?bar=15&oof=myp

Now lets say that I want to change the int value in the bar parameter to 16, in order to have

http://example.com/foo/?bar=16&oof=myp

How can I do this? Considering that the number after the = might be of 1, 2 or ever 3 characters. Thank you

Upvotes: 10

Views: 13718

Answers (2)

Max
Max

Reputation: 129

  1. Use regex to find the number parameter in the string url
  2. Use String.replace() to replace the old parameter with the new parameter

Upvotes: -3

amicoderozer
amicoderozer

Reputation: 2154

You can use UriComponentsBuilder (it's part of Spring Web jar) like this:

String url = "http://example.com/foo/?bar=15&oof=myp";

UriComponentsBuilder urlBuilder = UriComponentsBuilder.fromUriString(url);

urlBuilder.replaceQueryParam("bar", 107);

String result = urlBuilder.build().toUriString();

Substitute 107 with the number you want. With this method you can have URI or String object from urlBuilder.

Upvotes: 15

Related Questions