3

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.

5 Answers 5

4

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"
Sign up to request clarification or add additional context in comments.

1 Comment

this one is great because it just cuts from the start of the string.
1
string.replaceAll(".*/users(/.*/.*)", "$1");

2 Comments

The second /.* is unnecessary. Besides, why use capturing groups at all? See my answer :-)
True, it is not necessary, but I think capturing groups are more understandable in terms of knowing what you are getting.
1
String rest = url.substring(url.indexOf("/users/") + 6);

1 Comment

The OP wants to keep the last slash from /users/.
1

You can use split(String regex,int limit) which will split the string around the pattern in regex at most limit times, so...

String url="http://myurl.com/users/232222232/pageid";
String[] parts=url.split("/users",1);
//parts={"http://myurl.com","/232222232/pageid"}
String rest=parts[1];
//rest="/232222232/pageid"

The limit is there to prevent strings like "http://myurl.com/users/232222232/users/pageid" giving answers like "/232222232".

1 Comment

I would add a limit argument (1) to that split function.
0

You can use String.indexOf() and String.substring() in order to achieve this:

String pattern = "/users/";
String url = "http://myurl.com/users/232222232/pageid";
System.out.println(url.substring(url.indexOf(pattern)+pattern.length()-1);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.