2

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?

2
  • You can use Regex to do split and get the portion. Commented Sep 11, 2019 at 14:27
  • Specific Regex suggestions from the gurus are much appreciated. Commented Sep 11, 2019 at 15:07

4 Answers 4

3

Try passing the url string into a URL object and then pulling out the required segments:

URL someURL = new URL("https://myapp-dev.myhost.com/app/");
System.out.println("PATH = " + someURL.getPath());
System.out.println("HOST = " + someURL.getHost());
System.out.println("PROTOCOL = " + someURL.getProtocol());
System.out.println("PORT = " + someURL.getPort());

output:

PATH = /app/

HOST = myapp-dev.myhost.com

PROTOCOL = https

PORT = 8080

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks but I lose the port: http://localhost:8080/app --> localhost with HOST
this will throw exception on localhost:8080/myapp because URL requires schema. In URI schema is optional (but still don't match your case). OP might be better off with a regex
True, a MalformedURLException will be thrown if no protocol is defined.
There's some other problems with this: Let's say I don't just need the first term, I need all terms prior to the last one. Like http://myapp.host.com/part1/part2/. I still want everything before part2.
1

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

2 Comments

Was hoping to avoid this indexOf but looks like nothing else is as reliable. thanks
@geneb. You're welcome. I've edited my answer. May be the second aproach is a bit shorter.
0

You can split the string using a regular expression as I have mentioned in the comment. I provide below the Regex.

^https?:\/\/\w+(:[0-9]*)?(\.\w+)?

You can try with the following examples.

https://mydomain:8080

http://localhost:8090

You can also verify in https://rubular.com/ by pasting the regular expression and the example strings.

1 Comment

Thanks, however these strings don't match correctly to the last segment. http://myapp-dev.host.com/app/, http://app.host.com:8080/app/app2
0

Use String.lastIndexOf and String.substring to strip off last component.

Something like:

private String stripLastComponent(String path) {
    int n = path.lastIndexOf('/');
    if(n < 0) { // no / in path
        return path;
    }
    String stripped = path.substring(0, n);
    if(n == path.length()) { // '/' was last char, so try stripping again
        stripped = stripLastComponent(stripped);
    }
    return stripped;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.