How to obtain the last path segment of a URI

JavaStringUrl

Java Problem Overview


I have as input a string that is a URI. how is it possible to get the last path segment (that in my case is an id)?

This is my input URL:

String uri = "http://base_path/some_segment/id"

and I have to obtain the id I have tried with this:

String strId = "http://base_path/some_segment/id";
strId = strId.replace(path);
strId = strId.replaceAll("/", "");
Integer id =  new Integer(strId);
return id.intValue();

but it doesn't work, and surely there must be a better way to do it.

Java Solutions


Solution 1 - Java

is that what you are looking for:

URI uri = new URI("http://example.com/foo/bar/42?param=true");
String path = uri.getPath();
String idStr = path.substring(path.lastIndexOf('/') + 1);
int id = Integer.parseInt(idStr);

alternatively

URI uri = new URI("http://example.com/foo/bar/42?param=true");
String[] segments = uri.getPath().split("/");
String idStr = segments[segments.length-1];
int id = Integer.parseInt(idStr);

Solution 2 - Java

import android.net.Uri;
Uri uri = Uri.parse("http://example.com/foo/bar/42?param=true");
String token = uri.getLastPathSegment();

Solution 3 - Java

Here's a short method to do it:

public static String getLastBitFromUrl(final String url){
    // return url.replaceFirst("[^?]*/(.*?)(?:\\?.*)","$1);" <-- incorrect
    return url.replaceFirst(".*/([^/?]+).*", "$1");
}

Test Code:

public static void main(final String[] args){
    System.out.println(getLastBitFromUrl(
        "http://example.com/foo/bar/42?param=true"));
    System.out.println(getLastBitFromUrl("http://example.com/foo"));
    System.out.println(getLastBitFromUrl("http://example.com/bar/"));
}

Output:

> 42
> foo
> bar

Explanation:

.*/      // find anything up to the last / character
([^/?]+) // find (and capture) all following characters up to the next / or ?
         // the + makes sure that at least 1 character is matched
.*       // find all following characters


$1       // this variable references the saved second group from above
         // I.e. the entire string is replaces with just the portion
         // captured by the parentheses above

Solution 4 - Java

I know this is old, but the solutions here seem rather verbose. Just an easily readable one-liner if you have a URL or URI:

String filename = new File(url.getPath()).getName();

Or if you have a String:

String filename = new File(new URL(url).getPath()).getName();

Solution 5 - Java

If you are using Java 8 and you want the last segment in a file path you can do.

Path path = Paths.get("example/path/to/file");
String lastSegment = path.getFileName().toString();

If you have a url such as http://base_path/some_segment/id you can do.

final Path urlPath = Paths.get("http://base_path/some_segment/id");
final Path lastSegment = urlPath.getName(urlPath.getNameCount() - 1);

Solution 6 - Java

In Android

Android has a built in class for managing URIs.

Uri uri = Uri.parse("http://base_path/some_segment/id");
String lastPathSegment = uri.getLastPathSegment()

Solution 7 - Java

If you have commons-io included in your project, you can do it without creating unecessary objects with org.apache.commons.io.FilenameUtils

String uri = "http://base_path/some_segment/id";
String fileName = FilenameUtils.getName(uri);
System.out.println(fileName);

Will give you the last part of the path, which is the id

Solution 8 - Java

In Java 7+ a few of the previous answers can be combined to allow retrieval of any path segment from a URI, rather than just the last segment. We can convert the URI to a java.nio.file.Path object, to take advantage of its getName(int) method.

Unfortunately, the static factory Paths.get(uri) is not built to handle the http scheme, so we first need to separate the scheme from the URI's path.

URI uri = URI.create("http://base_path/some_segment/id");
Path path = Paths.get(uri.getPath());
String last = path.getFileName().toString();
String secondToLast = path.getName(path.getNameCount() - 2).toString();

To get the last segment in one line of code, simply nest the lines above.

Paths.get(URI.create("http://base_path/some_segment/id").getPath()).getFileName().toString()

To get the second-to-last segment while avoiding index numbers and the potential for off-by-one errors, use the getParent() method.

String secondToLast = path.getParent().getFileName().toString();

Note the getParent() method can be called repeatedly to retrieve segments in reverse order. In this example, the path only contains two segments, otherwise calling getParent().getParent() would retrieve the third-to-last segment.

Solution 9 - Java

You can use getPathSegments() function. (Android Documentation)

Consider your example URI:

String uri = "http://base_path/some_segment/id"

You can get the last segment using:

List<String> pathSegments = uri.getPathSegments();
String lastSegment = pathSegments.get(pathSegments.size - 1);

lastSegment will be id.

Solution 10 - Java

You can also use replaceAll:

String uri = "http://base_path/some_segment/id"
String lastSegment = uri.replaceAll(".*/", "")

System.out.println(lastSegment);

result:

id

Solution 11 - Java

I'm using the following in a utility class:

public static String lastNUriPathPartsOf(final String uri, final int n, final String... ellipsis)
  throws URISyntaxException {
	return lastNUriPathPartsOf(new URI(uri), n, ellipsis);
}

public static String lastNUriPathPartsOf(final URI uri, final int n, final String... ellipsis) {
	return uri.toString().contains("/")
	    ? (ellipsis.length == 0 ? "..." : ellipsis[0])
		  + uri.toString().substring(StringUtils.lastOrdinalIndexOf(uri.toString(), "/", n))
	    : uri.toString();
}

Solution 12 - Java

you can get list of path segments from the Uri class

String id = Uri.tryParse("http://base_path/some_segment/id")?.pathSegments.last ?? "InValid URL";

It will return id if the url is valid, if it is invalid it returns "Invalid url"

Solution 13 - Java

Get URL from URI and use getFile() if you are not ready to use substring way of extracting file.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDX89BView Question on Stackoverflow
Solution 1 - JavasfusseneggerView Answer on Stackoverflow
Solution 2 - JavaColateralView Answer on Stackoverflow
Solution 3 - JavaSean Patrick FloydView Answer on Stackoverflow
Solution 4 - JavaJason CView Answer on Stackoverflow
Solution 5 - JavaWill HumphreysView Answer on Stackoverflow
Solution 6 - JavaBrill PappinView Answer on Stackoverflow
Solution 7 - JavaBnrdoView Answer on Stackoverflow
Solution 8 - Javajaco0646View Answer on Stackoverflow
Solution 9 - JavaSina MasnadiView Answer on Stackoverflow
Solution 10 - JavaKrzysztof CichockiView Answer on Stackoverflow
Solution 11 - JavaGerold BroserView Answer on Stackoverflow
Solution 12 - Javabalu kView Answer on Stackoverflow
Solution 13 - JavaNageswara RaoView Answer on Stackoverflow