-1

Im trying to match a filename parameter with a regex for validation. I'm having problems with hyphens after numbers...

string: Article_RAR_Scout_13-03-14.pptx

regex:

private bool IsValidFileName(string FileName)
    {
        if (Regex.IsMatch(FileName, @"^Article[A-Z]{3}_Scout_[0-31]-[0-12]-[0-99]\.pptx$"))
        {
            return true;
        }
        else
        {
            throw new Exception("Please provide a correct file name (e.g. Drillinginfo_WAF_Scout_13-03-14.pptx");
        }                     
    }
Hardgraf
  • 2,566
  • 4
  • 44
  • 77
  • Your issue is more than just matching hyphens. You will have a problem matching your numbers as [0-31], [0-12]. and [0-99] are not valid character classes. I'd suggest you look for RegEx to match dates as that is what appears you are trying to do. For example, [Need regular expression for validating date in dd-MMM-yyyy format](http://stackoverflow.com/questions/10931179/need-regular-expression-for-validating-date-in-dd-mmm-yyyy-format) – psubsee2003 Jul 04 '14 at 11:56
  • Check your regex on regexr.com it helps a lot :) – Dominik Antal Jul 04 '14 at 11:56
  • @CodeCaster I disagree with the duplicate on the premise that the OP's problem here is much larger than just the title. There are probably better duplicates for matching dates. – psubsee2003 Jul 04 '14 at 11:57
  • @psubsee2003 then "this regex doesn't work, fix it for me" should be closed as too broad. Each sub-problem with this regex has already been solved on this site, feel free to find other questions that address OP's issues and link them in comments. – CodeCaster Jul 04 '14 at 11:58
  • @CodeCaster not disagreeing there. I never said it wasn't too broad or shouldn't be closed (hence my lack of a reopen vote), I was just pointing out the OP's problem is not the hyphen and is with matching the date. – psubsee2003 Jul 04 '14 at 12:00
  • I scanned title, description ("having problems") and code (saw hyphens) and dupe-closed with the first duplicate Google gave me. If OP wants a more specific duplicate, the "problems" should be described better. Thanks for your comment. See for example [Regular expression for specific number of digits](http://stackoverflow.com/questions/16373895/regular-expression-for-specific-number-of-digits), [how to extract date from a string using regex](http://stackoverflow.com/questions/14436188/how-to-extract-date-from-a-string-using-regex) and so on. – CodeCaster Jul 04 '14 at 12:01

1 Answers1

1

In the character class 0 to 9 [0-9] only possible, 0 to 31 [0-31] won't be possible. That's the problem with your regex and not with the hypens. And your regex would be,

^Article_[A-Z]{3}_Scout_(?:0[1-9]|[1-2][0-9]|3[01])-(?:0[1-9]|1[012])-(?:[1-9][0-9]|0[1-9])\.pptx

DEMO

Avinash Raj
  • 172,303
  • 28
  • 230
  • 274