Java 8 Get full URL path without last segment (with or without trailing slash)

gene b. :

I have URLs as below and need to trim them as follows without the last segment. There may or may not be a trailing slash.

localhost:8080/myapp -> localhost:8080/

https://myapp-dev.myhost.com/app/ -> https://myapp-dev.myhost.com/

https://myapp-dev.myhost.com/app/app2 -> https://myapp-dev.myhost.com/app/

Of course I could try solutions like

String[] tokens = uri.split("/"); // then concatenate previous ones...

or

Path path = Paths.get(uri.getPath());
String secondToLast = path.getName(path.getNameCount() - 2).toString();

But isn't there some more robust utility or method?

Eritrean :

If all you need is to trim everything after the last "/" (or the second last if the string ends with "/") may be a simple function could solve this:

public static void main(String[] args){ 

    Function<String,String> trimUrlString = s -> { 
        s = s.endsWith("/") ? s.substring(0, s.length()-1) : s;
        return  s.substring(0, s.lastIndexOf('/')+1);
    };

    String u1 = "localhost:8080/myapp";        
    System.out.println(trimUrlString.apply(u1));
    String u2 = "https://myapp-dev.myhost.com/app/";     
    System.out.println(trimUrlString.apply(u2));        
}
//output: localhost:8080/      https://myapp-dev.myhost.com/

EDIT

Another aproach which might be shorter is to chain two replaceAll calls :

myString.replaceAll("/$", "").replaceAll("/[^/]+$", "/");

The first call will remove a forward slash at the end if any, if there is no slash at the end myString remains the same. The second call will then replace every char after the last / which is not a /

Some test cases with your examples:

    String[] urls = {"localhost:8080/myapp",
                     "https://myapp-dev.myhost.com/app/test.pdf",
                     "http://myapp-dev.host.com/app/", 
                     "http://app.host.com:8080/app/app2"};

    for(String url : urls){
        String s = url.replaceAll("/$", "").replaceAll("/[^/]+$", "/");
        System.out.println(url);
        System.out.println(s); 
        System.out.println();
    }

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=329596&siteId=1