繁体   English   中英

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

[英]java: replace string in url between last 2 slashes /

我有一个网址: http//example.com8080 / files / username / oldpassword/12351.png

我需要用以下新密码替换oldpassword:

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

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

任何帮助非常感谢。

使用正则表达式

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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