我有一个像这样的网址: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);
}
我认为可以使用正则表达式来完成。
非常感谢任何帮助。
最佳答案
使用正则表达式
String out = url.replaceFirst("(.*/)(.*)(/[^/]*)", "$1" + newPass + "$3");
url = out;
关于java:替换 url 中最后 2 个斜杠之间的字符串/,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53032062/