3

I'm trying extract a substring from a string that contains a filename or directory. The substring being extracted should be the file extension. I've done some searching online and discovered I can use regular expressions to accomplish this. I've found that ^\.[\w]+$ is a pattern that will work to find file extensions. The problem is that I'm not fully familiar with regular expressions and its functions.

Basically If i have a string like C:\Desktop\myFile.txt I want the regular expression to then find and create a new string containing only .txt

Christopher Bottoms
  • 10,669
  • 8
  • 48
  • 97
user3657834
  • 219
  • 3
  • 9
  • 20

3 Answers3

21

Regex to capture file extension is:

(\\.[^.]+)$

Note that dot needs to be escaped to match a literal dot. However [^.] is a character class with negation that doesn't require any escaping since dot is treated literally inside [ and ].

\\.        # match a literal dot
[^.]+      # match 1 or more of any character but dot
(\\.[^.]+) # capture above test in group #1
$          # anchor to match end of input
anubhava
  • 713,503
  • 59
  • 514
  • 593
4

You could use String class split() function. Here you could pass a regular expression. In this case, it would be "\.". This will split the string in two parts the second part will give you the file extension.

public class Sample{
  public static void main(String arg[]){
    String filename= "c:\\abc.txt";

    String fileArray[]=filename.split("\\.");

    System.out.println(fileArray[fileArray.length-1]); //Will print the file extension
  }
}
Touchstone
  • 5,144
  • 7
  • 38
  • 48
2

If you don't want to use RegEx you can go with something like this:

String fileString = "..." //this is your String representing the File
int lastDot = fileString.lastIndexOf('.');
String extension = fileString.subString(lastDot+1);
Frank Andres
  • 146
  • 5