13

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.

TylerH
  • 20,799
  • 66
  • 75
  • 101
zxc
  • 1,504
  • 3
  • 13
  • 32

2 Answers2

30

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?$");
Brian Kintz
  • 1,983
  • 15
  • 19
  • Instead of using ToUpper you could use Equals with InvariantCultureIgnoreCase instead, it's way clearer – Mafii Dec 22 '22 at 07:27
5

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.

npinti
  • 51,780
  • 5
  • 72
  • 96