1

I have a String like this

String str = "www.google.com/..../upload/FileName.zip

I want to extract the string "FileName" from above string. I tried substr() method but couldn't found any solution.

SeekingAlpha
  • 7,489
  • 12
  • 35
  • 44
user3177222
  • 261
  • 2
  • 3
  • 11

4 Answers4

2

You can try this

    String str = "www.google.com/..../upload/FileName.zip";
    File file=new File(str);
    String fileName=file.getName();// now fileName=FileName.zip
    System.out.println(fileName.split("\\.")[0]);

Out put:

    FileName
Ruchira Gayan Ranaweera
  • 34,993
  • 17
  • 75
  • 115
2

Is it what you are looking for ?

  String lastPart= yourUrl.substring(yourUrl.lastIndexOf('/')+1, yourUrl.length());
  String fileName = lastPart.substring(0, lastPart.lastIndexOf('.'));

Considering the given format won't change.

Demo

Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
1

To get the part between the last slash and the dot:

String filename = str.replaceAll(".*?(?:/(\\w+)\\.\\w+$)?", "$1");

This regex has some special sauce added to return a blank if the target isn't found, by making the target optional and the leading expression reluctant.

Bohemian
  • 412,405
  • 93
  • 575
  • 722
  • Aren't anchors needed? – Justin Feb 03 '14 at 05:26
  • @Quincunx yeah thx - added end anchor $. Don't need start anchor. – Bohemian Feb 03 '14 at 05:47
  • This is exactly the method I was thinking of; I rather like regular expressions. This is clear. I can easily tell what it is doing. On the other hand, for some of these other answers, I find it less clear. – Justin Feb 03 '14 at 05:51
  • @quincunx I've added a bit of Kung Fu to the regex so it returns blank if a filename is not found. There's no way a non-regex approach with this behaviour could be done so succinctly. – Bohemian Feb 03 '14 at 06:29
  • And now I wish I could give 3 upvotes. I'd definitely call this the best answer, though if this is used in some shared situation, it would probably be better to use the regex form with comments, so noobs who don't know regex can understand what this does. – Justin Feb 03 '14 at 07:27
  • 1
    @Quincunx you can donate regex-fu rep by upvoting [this](http://stackoverflow.com/questions/17985909/regex-pattern-for-split/17986078#comment26296217_17986078) - I'm going to try to turn that low voted (but pretty good imho) answer into a [reversal](http://stackoverflow.com/help/badges/95/reversal) – Bohemian Feb 04 '14 at 13:40
0

Try this

String str = "www.google.com/..../upload/FileName.zip";
    String  str1[] = str.split("/");
    String file=str1[str1.length-1];
    String fileName=file.substring(0, file.lastIndexOf("."));
    System.out.println(fileName);

Output

FileName
Coder
  • 6,948
  • 13
  • 56
  • 86