[英]Deleting everything except last part of a String?
What kind of method would I use to make this: 我将使用哪种方法进行此操作:
http://www.site.net/files/file1.zip
To 至
file1.zip
? file1.zip
?
String yourString = "http://www.site.net/files/file1.zip";
int index = yourString.lastIndexOf('/');
String targetString = yourString.substring(index + 1);
System.out.println(targetString);// file1.zip
String str = "http://www.site.net/files/file1.zip";
str = str.substring(str.lastIndexOf("/")+1);
You could use regex to extract the last part: 您可以使用正则表达式提取最后一部分:
@Test
public void extractFileNameFromUrl() {
final Matcher matcher = Pattern.compile("[\\w+.]*$").matcher("http://www.site.net/files/file1.zip");
Assert.assertEquals("file1.zip", matcher.find() ? matcher.group(0) : null);
}
It'll return only "file1.zip". 它只会返回“ file1.zip”。 Included here as a test as I used it to validate the code.
当我使用它来验证代码时,此处包含为测试。
Use split: 使用拆分:
String[] arr = "http://www.site.net/files/file1.zip".split("/");
Then: 然后:
String lastPart = arr[arr.length-1];
Update: Another simpler way to get this: 更新:另一个更简单的方法来获得此:
File file = new File("http://www.site.net/files/file1.zip");
System.out.printf("Path: [%s]%n", file.getName()); // file1.zip
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.