Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Need to Trim Java String

Tags:

java

I need help in trimming a string url.

Let's say the String is http://myurl.com/users/232222232/pageid

What i would like returned would be /232222232/pageid

Now the 'myurl.com' can change but the /users/ will always be the same.

like image 422
user979587 Avatar asked Jan 01 '26 00:01

user979587


2 Answers

I suggest you use substring and indexOf("/users/").

String url = "http://myurl.com/users/232222232/pageid";
String lastPart = url.substring(url.indexOf("/users/") + 6);

System.out.println(lastPart);     // prints "/232222232/pageid"

A slightly more sophisticated variant would be to let the URL class parse the url for you:

URL url = new URL("http://myurl.com/users/232222232/pageid");
String lastPart = url.getPath().substring(6);

System.out.println(lastPart);     // prints "/232222232/pageid"

And, a third approach, using regular expressions:

String url = "http://myurl.com/users/232222232/pageid";
String lastPart = url.replaceAll(".*/users", "");

System.out.println(lastPart);     // prints "/232222232/pageid"
like image 188
aioobe Avatar answered Jan 02 '26 12:01

aioobe


string.replaceAll(".*/users(/.*/.*)", "$1");
like image 39
Garrett Hall Avatar answered Jan 02 '26 13:01

Garrett Hall