简体   繁体   中英

java: replace string in url between last 2 slashes /

i have a url like: http://example.com:8080/files/username/oldpassword/12351.png

i need to replace oldpassword with: new password.

oldpassword is not fixed string, it's unknown string.

currently i use this code:

String url = "http://example.com:8080/files/username/oldpassword/12351.png";
String[] split = url.split("/");
String oldPass = split[5];
String newPass = "anyNewRandomPassword";
if( !oldPass.equals(newPass)) {
     url = url.replace(oldPass, newPass);
}

i think it can be done using regex.

any help s much appreciated.

Using regex

String out = url.replaceFirst("(.*/)(.*)(/[^/]*)", "$1" + newPass + "$3");
url = out;

I think the AntPathMatcher is pretty handy for this kind of task and created a Scratch file for you. Hope this helps!

import org.springframework.util.AntPathMatcher;

import java.util.Map;

class Scratch {
    public static void main(String[] args) {
        final String givenUrl = "http://example.com:8080/files/username/oldpassword/12351.png\"";

        AntPathMatcher antPathMatcher = new AntPathMatcher();

        System.out.println("Analyse url '" + givenUrl + "'");
        Map<String, String> stringStringMap = antPathMatcher.extractUriTemplateVariables("**/{username}/{password}/**.**", givenUrl);

        String username = stringStringMap.get("username");
        String oldPassword = stringStringMap.get("password");
        System.out.println("username '" + username + "' + oldPassword '" + oldPassword + "'");

        String newPassword = "myNewSuperSecurePassword";
        System.out.println("Replacing it with new password '" + newPassword + ' ');

        String resultUrl = "";
        if(!newPassword.equals(oldPassword)){
            System.out.println("PASSWORD REPLACEMENT: New Password != old password and will be replaced");
            resultUrl = givenUrl.replace(oldPassword, newPassword);
        }else {
            System.out.println("NO REPLACEMENT: New Password equals old password");
            resultUrl = givenUrl;
        }

        System.out.println("Result URL '" + resultUrl + "'");
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM