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

2
  • For you: regular-expressions.info (A great resource that has many language-independent and language-specific aids.) Commented Apr 3, 2015 at 16:35
  • OP just wants to extract extension which is not what has been asked in dupe question. Commented Jan 29, 2021 at 5:45

3 Answers 3

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
Sign up to request clarification or add additional context in comments.

3 Comments

I don't think a space can be part of a file extension? Perhaps [\w] or [^\s] instead of [^.]?
@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
Sure, but I really doubt that would count as a file extension, just a file with a dot in its name. My 2¢.
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
  }
}

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.