1

i have a url like: http://example.com:8080/files/username/oldpassword/12351.png

i need to replace oldpassword with: new password.

oldpassword is not fixed string, it's unknown string.

currently i use this code:

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

i think it can be done using regex.

any help s much appreciated.

Yitian Zhang
  • 314
  • 1
  • 3
  • 18
Mohammed Ahmed
  • 431
  • 5
  • 11

2 Answers2

2

Using regex

String out = url.replaceFirst("(.*/)(.*)(/[^/]*)", "$1" + newPass + "$3");
url = out;
Joakim Danielson
  • 43,251
  • 5
  • 22
  • 52
1

I think the AntPathMatcher is pretty handy for this kind of task and created a Scratch file for you. Hope this helps!

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 + "'");
    }
}
Lennart Blom
  • 513
  • 3
  • 19
  • some times the String url = "http://example.com:8080/username/oldpassword/12351.png"; and String url = "http://example.com:8080/username/oldpassword/12351"; how can i extract the password? – Mohammed Ahmed Nov 05 '18 at 10:55
  • Try this new call with a modified pattern: `antPathMatcher.extractUriTemplateVariables("**/{username}/{password}/*", givenUrl);` This works for me! :) – Lennart Blom Nov 05 '18 at 13:59
  • Did this new pattern help you? – Lennart Blom Nov 06 '18 at 14:25
  • i used: String url = "http://example.com:8080/files/user1/password123/12351.png"; String[] split = url.split("/"); System.out.println(split[split.length - 2]); – Mohammed Ahmed Nov 15 '18 at 23:13