zxc
zxc

Reputation: 1526

C# Regex that matches Excel file extensions

I need a regex for my file upload to choose only Excel files I tried using this as my pattern(below)

Regex reg = new Regex("^.\.(xls|xlsx)");

Unfortunately I can't escape the "\." part of the the pattern.

Upvotes: 13

Views: 26361

Answers (2)

Brian Kintz
Brian Kintz

Reputation: 1993

A better method would be to use Path.GetExtension, then compare the results:

var filepath = @"C:\path\to\file.xls";
var extension = Path.GetExtension(filepath).ToUpper();

if (extension == ".XLS" || extension == ".XLSX") {
    // is an Excel file
}

To answer the original question, to match filepaths with.xls or .xlsx as a file extension, use the following regex:

var regex = new Regex(@".*\.xlsx?$");

Upvotes: 30

npinti
npinti

Reputation: 52185

Just add another \ or add the @ in front of the string like so: "^.\\.(xls|xlsx)" or @"^.\.(xls|xlsx)"

Also, I am assuming that you shall be matching the extension of the file with that regex, and not the actual file name itself, since that regex will match anything which starts with .xls or .xlsx.

Upvotes: 5

Related Questions