[英]Parse string value from URL
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 我在这种模式下有一个字符串(这是一个URL)
https://xxx.kflslfsk.com/kjjfkskfjksf/v1/files/media/93939393hhs8.jpeg
现在我想将其剪切至此
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: 我是Java的新手,但是在Swift(iOS)中,这就是我们的操作方式:
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. 基本上,我将从最后2个项目的网址期望中删除所有内容,然后删除。
I'm joining those 2 items using /
. 我正在使用
/
加入这2个项目。
String ret = url.substring(url.indexof("media"),url.indexof("jpg"))
Are you familiar with Regex? 您熟悉Regex吗? Try to use this Regex (explained in the link) that captures the last 2 items separated with
/
: 尝试使用此正则表达式 (在链接中解释),该正则表达式捕获用
/
分隔的最后2个项目。
.*?\/([^\/]+?\/[^\/]+?$)
Here is the example in Java (don't forget the escaping with \\\\
: 这是Java中的示例(不要忘记使用
\\\\
进行转义:
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. 另外,还有
split(..)
函数,但是我建议您采用上述方法。 (Finally concatenate separated strings correctly with StringBuilder
). (最后使用
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
两者给出的结果相同:
media/93939393hhs8.jpeg
string result=url.substring(url.substring(0,url.lastIndexOf('/')).lastIndexOf('/'));
or 要么
Use Split and add last 2 items 使用拆分并添加最后2个项目
string[] arr=url.split("/");
string result= arr[arr.length-2]+"/"+arr[arr.length-1]
public static String parseUrl(String str) {
return (str.lastIndexOf("/") > 0) ? str.substring(1+(str.substring(0,str.lastIndexOf("/")).lastIndexOf("/"))) : str;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.