Search code examples
javastringstring-matching

How can I manipulate this string in order to find and change a section of my original string in Java?


I am working on a Java application and I have the following problem.

I have a string like this (representing the URL of an API endpoint):

https://www.XXX.it/wp-json/custom-api/notary?title=Marina%20Rossi&wpcf-idnotary=089cy5Ra9zE=&wpcf-nome-notary=Marina....................

For some reason, I must replace the value of the idnotary query parameter with another value. I can do it only directly on this string and not when I am adding parameters, so my question is based on how to perform this string manipulation and not how to add parameters to a request.

Basically, I need a way that starting from this string replace the value after idnotary= and before &wpcf-nome-notary with another string represented by another variable in my application.

In practice, this value or the previous string 089cy5Ra9zE must be identified and replaced in the original string (considering that it can change because every request will have a different value).


Solution

  • public static String replaceIdnotary(String url,String newIdnotary){
        return url.replaceAll("(?<=wpcf-idnotary=)[^&]*",newIdnotary);
      }