简体   繁体   中英

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 ?

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". 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM