Reputation: 1323
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
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
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
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
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
Reputation: 13002
Use the URL class, it splits up a url in all the relevant parts: http://docs.oracle.com/javase/7/docs/api/java/net/URL.html
http://docs.oracle.com/javase/7/docs/api/java/net/URL.html#URL(java.lang.String)
Upvotes: 1