我目前正在寻找一个正则表达式,可以帮助验证文件的路径,例如:
C:\测试\ TEST2 \ test.exe的
解决方案
我决定发布这个答案,不使用常规的EX pression。
^([A-ZA-Z] \:|?\\\\ + [。\ W \] \\ [。\ w $] +)\\( ?[\ w] + \\)* \ W([\ W])+ $
可用于这些:
\\测试\测试$ \ TEST.XLS
\\服务器\共享\文件夹\ myfile.txt的
\\服务器\共享\ myfile.txt的
\\ 123.123.123.123 \共享\文件夹\ myfile.txt的
C:\文件夹\ myfile.txt的
C:\文件夹\ myfileWithoutExtension
编辑:添加例子用法:
如果(Regex.IsMatch(文字,@^([A-ZA-Z] \:|?\\\\ + \ W \。] \\ [ \ W $] +)\\(?:[\ w] + \\)* \ W([\ w])+ $))
{
// 有效
}
*编辑:*这是你可以看到路径的近似值。如果可能的话,它可能是最好使用Path类或FileInfo类,看是否有文件或文件夹是否存在。
I am currently looking for a regex that can help validate a file path e.g.:
C:\test\test2\test.exe
解决方案
I decided to post this answer which does use a regular expression.
^(?:[a-zA-Z]\:|\\\\[\w\.]+\\[\w.$]+)\\(?:[\w]+\\)*\w([\w.])+$
Works for these:
\\test\test$\TEST.xls
\\server\share\folder\myfile.txt
\\server\share\myfile.txt
\\123.123.123.123\share\folder\myfile.txt
c:\folder\myfile.txt
c:\folder\myfileWithoutExtension
Edit: Added example usage:
if (Regex.IsMatch (text, @"^(?:[a-zA-Z]\:|\\\\[\w\.]+\\[\w.$]+)\\(?:[\w]+\\)*\w([\w.])+$"))
{
// Valid
}
*Edit: * This is an approximation of the paths you could see. If possible, it is probably better to use the Path class or FileInfo class to see if a file or folder exists.