6

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
  • 11,218
  • 8
  • 50
  • 99
user3657834
  • 249
  • 4
  • 9
  • 21

3 Answers3

22

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
  • 761,203
  • 64
  • 569
  • 643
  • I don't think a space can be part of a file extension? Perhaps `[\w]` or `[^\s]` instead of `[^.]`? – Inigo Aug 16 '22 at 06:58
  • @Inigo: A unix file system allows any character to be used as extension. I can create a file with the name `a.b c` as well – anubhava Aug 16 '22 at 07:00
  • Sure, but I really doubt that would count as a file extension, just a file with a dot in its name. My 2¢. – Inigo Aug 16 '22 at 07:03
6

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,575
  • 7
  • 41
  • 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