"http://m.facebook.com/category/1231/messages"; I want to fetch the 1231 from the specified Url. I have a lot of url's in which i need to do the same. I need generic implementation of it.
Asked
Active
Viewed 99 times
2 Answers
2
Like this:
URI uri = new URI("http://m.facebook.com/category/1231/messages");
String[] parts = uri.getPath().split("/");
String stringId = parts[parts.length-1];
int id = Integer.parseInt(stringId);

MShaposhnik
- 56
- 4
-
what if the url is like this "m.facebook.com/category/String/messages and i wanted to get the String – Shuchita Apr 30 '15 at 14:05
-
If it can be a string, you need to test is stringId variable is a numeric. Examples is [here](http://stackoverflow.com/questions/1102891/how-to-check-if-a-string-is-a-numeric-type-in-java) – MShaposhnik Apr 30 '15 at 14:27
-
That's the way to the solution. You actually want the element at `parts.length-2`. – vefthym May 02 '15 at 16:28
0
If the pattern is always like that:
"http://m.facebook.com/category/"+number+"/messages"
? and you only need to get the number, then, you can extract it as follows (according to this answer):
String url; // this is where the url is stored, from which you want to extract the number
int finalResult = Integer.parseInt(url.replaceAll("\\D", "")); //this removes from the url all the non-numeric characters and parses the resulting String to an Integer
This assumes that the only number appearing in the url is the number that you wish to extract.
UPDATE:
If the id can also be a String, then you can do as follows:
String tmpResult = url.substring(0, url.lastIndexOf("/"));
String finalResult = tmpResult.substring(tmpResult.lastIndexOf("/")+1);
UPDATE 2:
Since you don't want to use the lastIndexOf
method (for some reason), and since you might get a String as an id, here is what you can do (using much from MShaposhnik's answer):
String url; //the input
String finalResult; //the output
String[] split = url.split("/");
if (split.length > 2) {
finalResult = split[split.length-2];
}
-
what if the url is like this "http://m.facebook.com/category/String/messages and i wanted to get the String – Shuchita Apr 30 '15 at 14:03
-
@Shuchita, please see my updated answer, which is not probably optimal, but quite intuitive. I will see if I can improve it. – vefthym Apr 30 '15 at 14:07
-
-
Yes, there is MShaposhnik's way. You split the string by "/", into an array of size `n` and then you get the element at position `n-2`. – vefthym May 02 '15 at 16:22