Regex to get the file extension

I have a list containing 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 do not want to use String.Split, how to get the regular expression file extension?

+5
source share
6 answers

You do not need to use regex for this. You can use the method Path.GetExtension.

Gets the extension of the specified path string.

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

Here DEMO.

+13
source

You can use Path.GetExtension().

Example (also removes the point):

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

// extension now contains "ext"
+4
source

:

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

, , :

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

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

, 1 - ,


LastIndexOf ( "." )

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

.

+2

"\. [^ \.] +" , '.' , 1 . .

, , regex overkill .

0

-

, . FirstPart.SecondPart.xml .

Path.GetFileExtension() .

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

. 3 4 . Regexr. , .

, 3-4 , , , , , .

0
source

All Articles