Search code examples
.netregexvalidation-controls

valid regular regular expression string


Hi I have a regular expression which is strated failing now. not sure what is stopping.

Regex regex = new Regex(@"^(([a-zA-Z]:)|(\\{2}\w+\\[\w- ]+[$])|(\\{2}\w+))(\\[\w-. ]*)*(.xml|.XML)$");

if (!regex.IsMatch(fuSource.PostedFile.FileName))
{
      Page.Validators.Add(new ValidatorHelper("Please select a valid Application XML input file."));
}

the file name i am passing is:

XX2 03-01-2017.xml

But for some reason it is not taking.

please help with the valid file name that matches the pattern..


Solution

  • You can test your regex on an online tool like this one to try it yourself :
    https://regex101.com/r/UX9TjE/1

    Basically your regexp matches 3 parts in the filename :

    • The prefix : It can be 3 things
      • A windows-like drive name : c: or Z:
      • A windows shared drive with parameter : \\shared\user$
      • A windows shared drive : \\shared
    • The name (note: it can be empty, ie zero-length) :
      • It includes the path of the file, using backslashes, and it can have spaces :
      • \my\path\my file
    • The extension : .xml or .XML

    IMHO this regex is not very good, here are some example matches :

    c:\path\\XX2 03-01-2017.xml
    
    \\nas\user$\XX2 03-01-2017.xml
    
    \\network_shared\.xml
    
    \\a.XML
    

    You can see why each one matches here :
    https://regex101.com/r/UX9TjE/2