我有一个像这样的url: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);
}
我认为可以使用regex来完成。
如有任何帮助,我将不胜感激。
发布于 2018-10-29 02:11:54
使用正则表达式
String out = url.replaceFirst("(.*/)(.*)(/[^/]*)", "$1" + newPass + "$3");
url = out;
发布于 2018-10-29 01:41:22
我认为AntPathMatcher对于这类任务是非常方便的,它为你创建了一个临时文件。希望这能有所帮助!
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 + "'");
}
}
https://stackoverflow.com/questions/53032062
复制相似问题