1

How do I use regex to get a file extension?

 2 years ago
source link: https://www.codesd.com/item/how-do-i-use-regex-to-get-a-file-extension.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

How do I use regex to get a file extension?

advertisements

This question already has an answer here:

  • Java: splitting the filename into a base and extension 8 answers

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


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


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK