【问题标题】:java: replace string in url between last 2 slashes /java:在最后两个斜杠之间替换url中的字符串/
【发布时间】:2018-10-28 13:32:08
【问题描述】:

我有一个类似的网址: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);
}

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

非常感谢任何帮助。

【问题讨论】:

标签: java string replace


【解决方案1】:

使用正则表达式

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

【讨论】:

【解决方案2】:

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

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-04-21
  • 2020-05-04
  • 2014-02-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多