DX89B DX89B - 2 months ago 11x
Java Question

How to obtain the last path segment of an uri

I have in input a string that is an

. how is 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.replaceAll("/", "");
Integer id = new Integer(strId);
return id.intValue();

but it doesn't work and for sure there is a better way to do it

thx a lot


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


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