user3657834
user3657834

Reputation: 259

How to use regex to get file extension?

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

Upvotes: 6

Views: 34796

Answers (3)

Touchstone
Touchstone

Reputation: 5962

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
  }
}

Upvotes: 6

Frank Andres
Frank Andres

Reputation: 146

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);

Upvotes: 2

anubhava
anubhava

Reputation: 784898

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

Upvotes: 22

Related Questions