-2

I'm calling match below but I'm getting an exception that says "Internal error in the expression evaluator." when I try and pass "*_sales.txt" in as config.FileNamePattern. For some reason it doesn't like this pattern. What am I doing wrong? I tried passing it in with and without the '@' symbol.

Match match = Regex.Match(Path.GetFileName(file), @config.FileNamePattern, RegexOptions.IgnoreCase);
chuckd
  • 13,460
  • 29
  • 152
  • 331
  • 1
    Because you passed an invalid regex. It cannot start with a quantifier. Try `@"_sales\.txt$"` – Wiktor Stribiżew Sep 28 '16 at 21:08
  • 2
    and `*_sales.txt` isn't a valid pattern anyways. `*` is a quantifier, and you have nothing for it to quantify. `.*sales.txt` would be valid. – Marc B Sep 28 '16 at 21:08
  • Actually, I do not think the question is related to wildcards, just `*` was used as an incorrect regex pattern since OP thought it could be used as a regex, too. – Wiktor Stribiżew Sep 28 '16 at 21:39

1 Answers1

0

The second argument to Regex.Match is a regex pattern. You pass "*_sales.txt" that starts with a * that you think is a wildcard, but in fact is a quantifier matching zero or more occurrences. It cannot quantifier the beginning of a pattern, it is an invalid regex.

You might want to use

@"_sales\.txt$"

to check if a string ends with _sales.txt. Also, adding RegexOptions.RightToLeft to your options can optimize matching the string from the end.

Note the . is escaped to match a literal dot.

Also, a verbatim string literal is the best way to define regex patterns as you only have to escape the special chars once.

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563