Search code examples
javastringdesign-patternsmatcher

Replace a Param in QueryString in Java


lets say I have a url param like token=1234235asdjaklj231k209a&name=sam&firname=Mahan how can I replace the value of the token with new one ? I've done something similar to this with pattern and matcher before but I don't recall now but I know there is a way to do so Update : the token can contain any letter but & thanks in advance


Solution

  • We can consider doing a simple regex replacement, with a few caveats (q.v. below the code snippet).

    String url = "token=1234235asdjaklj231k209a&name=sam&firname=Mahan";
    url = url.replaceFirst("\\btoken=.*?(&|$)", "token=new_value$1");
    System.out.println(url);
    url = "param1=value&token=1234235asdjaklj231k209a";
    url = url.replaceFirst("\\btoken=.*?(&|$)", "token=new_value$1");
    System.out.println(url);
    

    Edge cases to consider are first that your token may be the last parameter in the query string. To cover this case, we should check for token=... ending in either an ambersand & or the end of the string. But if we don't use a lookahead, and instead consume that ambersand, we have to also add it back in the replacement. The other edge case, correctly caught by @DodgyCodeException in his comment below, is that there be another query parameter which just happens to end in token. To make sure we are really matching our token parameter, we can preface it with a word boundary in the regex, i.e. use \btoken=... to refer to it.

    Output:

    token=new_value&name=sam&firname=Mahan
    param1=value&token=new_value