4

I have URLs which always end on 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?

5 Answers 5

8

You could split the string:

String[] items = url.split("/");
String number = items[items.length-1]; //last item before the last slash
Sign up to request clarification or add additional context in comments.

Comments

2

With a regular expression:

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

Comments

1

Use lastIndexOf, like this:

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

That's the basic idea. You'll have to do some error checking (for example, if a number is not found at the end of the URL), but it will work fine.

Comments

1

For the inputs which 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 "/" like

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

Comments

1

In One Line :

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.