How to obtain the last path segment of a URI Ask Question

How to obtain the last path segment of a URI Ask Question

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.

ベストアンサー1

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

おすすめ記事