mithrandir
mithrandir

Reputation: 1323

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

Upvotes: 0

Views: 335

Answers (5)

Priyankchoudhary
Priyankchoudhary

Reputation: 836

To get the last part of the link, you can use the Uri class.

data = Uri.parse("https://example.com/abc/.../xyz/name_part");
data.getLastPathSegment();

Upvotes: 0

Ryan Stewart
Ryan Stewart

Reputation: 128919

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.

Upvotes: 2

Evgeniy Dorofeev
Evgeniy Dorofeev

Reputation: 136112

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]

Upvotes: 1

Chris
Chris

Reputation: 5654

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

Upvotes: 5

Related Questions