user339160
user339160

Reputation:

Regex to get the file extension

I have a list which contains file names (without their full path)

List<string> list=new List<string>();

list.Add("File1.doc");
list.Add("File2.pdf");
list.Add("File3.xls");

foreach(var item in list) {
    var val=item.Split('.');
    var ext=val[1];
}

I don't want to use String.Split, how will I get the extension of the file with regex?

Upvotes: 7

Views: 18903

Answers (6)

Siraf
Siraf

Reputation: 1300

"\\.[^\\.]+" matches anything that starts with . character followed by 1 or more no . characters.

By the way the others are right, regex is overkill here.

Upvotes: 0

JJJCoder
JJJCoder

Reputation: 16986

For the benefit of googlers -

I was dealing with bizarre filenames e.g. FirstPart.SecondPart.xml, with the extension being unknown.

In this case, Path.GetFileExtension() got confused by the extra dots.

The regex I used was

\.[A-z]{3,4}$

i.e. match the last instance of 3 or 4 characters with a dot in front only. You can test it here at Regexr. Not a prize winner, but did the trick.

The obvious flaw is that if the second part were 3-4 chars and the file had no extension, it would pick that up, however I knew that was not a situation I would encounter.

Upvotes: 2

MikeM
MikeM

Reputation: 13641

To get the extension using regex:

foreach (var item in list) {
    var ext = Regex.Match( item, "[^.]+$" ).Value;
}

Or if you want to make sure there is a dot:

@"(?<=\.)[^.]+$"

Upvotes: 6

Louis Ricci
Louis Ricci

Reputation: 21116

The regex is

\.([A-Za-z0-9]+)$

Escaped period, 1 or more alpha-numeric characters, end of string


You could also use LastIndexOf(".")

int delim = fileName.LastIndexOf(".");
string ext = fileName.Substring(delim >= 0 ? delim : 0);

But using the built in function is always more convenient.

Upvotes: 3

Soner G&#246;n&#252;l
Soner G&#246;n&#252;l

Reputation: 98868

You don't need to use regex for that. You can use Path.GetExtension method.

Returns the extension of the specified path string.

string name = "notepad.exe";
string ext = Path.GetExtension(name).Replace(".", ""); // exe

Here is a DEMO.

Upvotes: 16

mishmash
mishmash

Reputation: 4458

You could use Path.GetExtension().

Example (also removes the dot):

string filename  = "MyAwesomeFileName.ext";
string extension = Path.GetExtension(filename).Replace(".", ""); 

// extension now contains "ext"

Upvotes: 5

Related Questions