Regex - File Path - Windows

^(?:[a-zA-Z]:\\$)|^(?:[a-zA-Z]\:|\\)(\\(?!\.)(?!\s[a-zA-Z_0-9-\.])[a-zA-Z_\-\s0-9\.\$]+)+$

or 

^(\w:\\$)|^(?:[\w]\:|\\)(\\(?!\.)(?!\s[a-zA-Z_0-9-])[a-zA-Z_\-\s0-9\.\$]+)+$

NOTE: This is made up of:

  • ^(?:[a-zA-Z]:\\$): Caters for C:\.
  • ^(?:[a-zA-Z]\:|\\)(\\(?!\.)(?!\s[a-zA-Z_0-9-\.])[a-zA-Z_\-\s0-9\.\$]+)+$: Cater for UNC and standard files with a directory name.
  • ^(\w:\\$): Caters for C:\.
  • ^(?:[\w]\:|\\)(\\(?!\.)(?!\s[a-zA-Z_0-9-])[A-Za-z_\-\s0-9\.\$]+)+$: Cater for UNC and standard files with a directory name.

NOTE: This regex supports the following as valid.

c:\
c:\folder\myfile.txt
c:\folder\myfileWithoutExtension
c:\my folder\abc abc.docx
c:\my-folder\another_folder\abc.v2.docx
C:\pictures\holiday  
C:\pictures\holiday\ 
\\192.168.0.1\folder\file.pdf
\\192.168.0.1\my folder\folder.2\file.gif
\\10.30.28.52\CDSDataCenter\Servers\Continuous\CDS20$
\\server\filename
\\server\filename with space
\\test\test$\TEST.xls
\\server\share\folder\myfile.txt
\\server\share\myfile.txt
\\123.123.123.123\share\folder\myfile.txt

NOTE: The following are not valid:

file
file.xls
c:\my folder\another_folder\.docx
c:\my folder\\another_folder\abc.docx
c:\my folder\another_folder\ab*c.v2.docx
c:\my?folder\another_folder\abc.v2.docx
C:\ pictures\holiday
C:\ pictures\holiday\
C:\pictures \ holiday
C:\pictures \ holiday\
C:\pictures\ holiday \
\\192.168.0.1\folder\fi<le.pdf
\\192.168.0.1\folder\\file.pdf
\\192.168.0.1\my folder\folder.2\.gif
\\server\filename\{token}\file

To allow the top two entries to also be accepted as valid entries change the regex to include:

  • ^([A-Za-z_\-\s0-9\.\$]+)$: Caters for plain filenames, such as file.txt or file.
^(\w:\\$)|^([A-Za-z_\-\s0-9\.\$]+)$|^(?:[\w]\:|\\)(\\(?!\.)(?!\s[a-z_0-9-])[A-Za-z_\-\s0-9\.\$]+)+$

To allow the very bottom entry here: \\server\filename\{token}\file:

^(?:[a-zA-Z]:\\$)|^(?:[a-zA-Z]\:|\\)(\\(?!\.)(?!\s[a-zA-Z_0-9-\.])\{?[a-zA-Z_\-\s0-9\.\$]+)+(\}\\([a-zA-Z_\-\s0-9\.\$])+?)?$

References

https://www.regexpal.com/97685