Java: string slicing

I have URLs that always end with a number, for example:

String url = "localhost:8080/myproject/reader/add/1/"; String anotherurl = "localhost:8080/myproject/actor/take/154/"; 

I want to extract the number between the last two slashes ("/").

Does anyone know how I can do this?

+4
source share
5 answers

You can break the line:

 String[] items = url.split("/"); String number = items[items.length-1]; //last item before the last slash 
+8
source

With regex:

 final Matcher m = Pattern.compile("/([^/]+)/$").matcher(url); if (m.find()) System.out.println(m.group(1)); 
+2
source

Use lastIndexOf , for example:

  String url = "localhost:8080/myproject/actor/take/154/"; int start = url.lastIndexOf('/', url.length()-2); if (start != -1) { String s = url.substring(start+1, url.length()-1); int n = Integer.parseInt(s); System.out.println(n); } 

This is the main idea. You will need to do some error checking (for example, if the number is not found at the end of the URL), but it will work fine.

+1
source

For the inputs you specified

 String url = "localhost:8080/myproject/reader/add/1/"; String anotherurl = "localhost:8080/myproject/actor/take/154/"; 

adding a little error handling to handle missing "/", for example

 String url = "localhost:8080/myproject/reader/add/1"; String anotherurl = "localhost:8080/myproject/actor/take/154"; String number = ""; if(url.endsWith("/") { String[] urlComps = url.split("/"); number = urlComps[urlComps.length-1]; //last item before the last slash } else { number = url.substring(url.lastIndexOf("/")+1, url.length()); } 
+1
source

In one line:

  String num = (num=url.substring(0, url.length() - 1)).substring(num.lastIndexOf('/')+1,num.length()); 
+1
source

All Articles