DX89B DX89B - 1 year ago 131
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

Answer Source

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);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download