简体   繁体   中英

Dynamically extracting the last part of a URL

I have a URL https://xyz.com/abc/.../xyz/name_part . I would like to efficently split this into 2 separate parts a Namespace URI that is https://xyz.com/abc/.../xyz and to a Name part which is the name_part in the URL. What is the best way of doing this in Java? Note that the Namespace URI is not fixed and this can be dynamic. Cheers

From what I know, URL class of JDK can cater to your needs.

URL url = new URL("https://test:password@localhost:7001/context/document?key1=val1&key2=val2");

Check all the getters of URL class. some of them include:

url.getProtocol();
url.getUserInfo();
url.getHost();
url.getPort();
url.getPath();
url.getQuery();

It's highly unlikely that efficiency should be any concern in this. Go for what's most understandable:

String url = "https://xyz.com/abc/.../xyz/name_part";
int separator = url.lastIndexOf('/');
String namespacePart = url.substring(0, separator);
String namePart = url.substring(separator + 1);

or maybe:

String url = "https://xyz.com/abc/.../xyz/name_part";
String[] pathSegments = URI.create(url).getPath().split("/");
String namePart = pathSegments[pathSegments.length - 1];
String namespacePart = url.replaceAll("/" + namePart + "$", "");

depending on what seems most natural to you.

In this situation I would simply use regex

    String url = "https://xyz.com/abc/.../xyz/name_part";
    String[] a = url.split("/(?!.*/.*)");
    System.out.println(Arrays.toString(a));

output

[https://xyz.com/abc/.../xyz, name_part]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM