1

I have a string (which is an URL) in this pattern https://xxx.kflslfsk.com/kjjfkskfjksf/v1/files/media/93939393hhs8.jpeg now I want to clip it to this

media/93939393hhs8.jpeg

I want to remove all the characters before the second last slash /.

i'm a newbie in java but in swift (iOS) this is how we do this:

if let url = NSURL(string:"https://xxx.kflslfsk.com/kjjfkskfjksf/v1/files/media/93939393hhs8.jpeg"), pathComponents = url.pathComponents {
    let trimmedString = pathComponents.suffix(2).joinWithSeparator("/")
    print(trimmedString) // "output =  media/93939393hhs8.jpeg"
}

Basically, I'm removing everything from this Url expect of last 2 item and then.

I'm joining those 2 items using /.

2
  • what's your question? Commented Aug 26, 2016 at 16:05
  • get media/93939393hhs8.jpeg from https://xxx.kflslfsk.com/kjjfkskfjksf/v1/files/media/93939393hhs8.jpeg @Jean-FrançoisFabre Commented Aug 26, 2016 at 16:06

4 Answers 4

2
String ret = url.substring(url.indexof("media"),url.indexof("jpg"))
Sign up to request clarification or add additional context in comments.

Comments

1

Are you familiar with Regex? Try to use this Regex (explained in the link) that captures the last 2 items separated with /:

.*?\/([^\/]+?\/[^\/]+?$)

Here is the example in Java (don't forget the escaping with \\:

Pattern p = Pattern.compile("^.*?\\/([^\\/]+?\\/[^\\/]+?$)");
Matcher m = p.matcher(string);

if (m.find()) {
    System.out.println(m.group(1));
}

Alternatively there is the split(..) function, however I recommend you the way above. (Finally concatenate separated strings correctly with StringBuilder).

String part[] = string.split("/");
int l = part.length;
StringBuilder sb = new StringBuilder();
String result = sb.append(part[l-2]).append("/").append(part[l-1]).toString();

Both giving the same result: media/93939393hhs8.jpeg

Comments

1
 string result=url.substring(url.substring(0,url.lastIndexOf('/')).lastIndexOf('/'));

or

Use Split and add last 2 items

  string[] arr=url.split("/");
  string result= arr[arr.length-2]+"/"+arr[arr.length-1]

Comments

1
public static String parseUrl(String str) {
    return (str.lastIndexOf("/") > 0) ? str.substring(1+(str.substring(0,str.lastIndexOf("/")).lastIndexOf("/"))) : str;
}

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.