tags:

views:

64

answers:

3

I have in input a string that is an uri 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.replace(path);
    strId=strId.replaceAll("/", "");
    Integer id =  new Integer(strId);
    return id.intValue();

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

thx a lot

+5  A: 

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);
sfussenegger
A: 

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

hanks, Rao

Nageswara Rao
won't work, see javadoc of getFile(): Gets the file name of this URL. The returned file portion will be the same as getPath(), plus the concatenation of the value of getQuery(), if any. If there is no query portion, this method and getPath() will return identical results.)
sfussenegger
+3  A: 

Nice of you to accept the answer, but the version you accepted was actually incorrect. Update: it's no longer accepted. Heres a simpler correct version:

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
seanizer
i will try your too, but for now sfussenegger's code works very well and i have understand it, in your i don't understand this (".*/([^/?]+).*", "$1" part .
DX89B
no sweat, sfussenegger's answer is good, but I'll try to explain mine in a minute or so.
seanizer
thx for the explain i will try it
DX89B