java:在最后2个斜杠之间替换url中的字符串/

时间:2018-10-28 13:32:09

标签: java string replace

我的网址类似:http://example.com:8080/files/username/oldpassword/12351.png

我需要用新密码替换旧密码。

oldpassword不是固定的字符串,它是未知字符串。

当前我使用此代码:

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);
}

我认为可以使用正则表达式来完成。

非常感谢任何帮助。

2 个答案:

答案 0 :(得分:2)

使用正则表达式

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

答案 1 :(得分:1)

我认为AntPathMatcher对于此类任务非常方便,并为您创建了一个Scratch文件。希望这会有所帮助!

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 + "'");
    }
}