测试语法正确的路径

发布于 2024-07-09 02:36:04 字数 296 浏览 8 评论 0原文

.NET 中是否有一个函数可以测试字符串在语法上是否是正确的路径? 我特别不想让它测试路径是否确实存在。

我目前对此的看法是正则表达式:

([a-zA-Z]:|\\)?\\?([^/\\:*?"<>|]+[/\\])*[^/\\:*?"<>|]*

匹配:

c:\
bbbb
\\bob/john\
..\..\

拒绝:

xy:
c:\\bob

In .NET is there a function that tests if a string is syntactically a correct path? I specifically don't want it to test if the path actually exists.

my current take on this is a regex:

([a-zA-Z]:|\\)?\\?([^/\\:*?"<>|]+[/\\])*[^/\\:*?"<>|]*

matches:

c:\
bbbb
\\bob/john\
..\..\

rejects:

xy:
c:\\bob

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

作妖 2024-07-16 02:36:04

我相信如果 System.IO.Path.GetFullPath(path) 不是语法上正确的路径而不检查它是否存在,则会抛出异常。

I believe System.IO.Path.GetFullPath(path) will throw an exception if it is not a syntactically correct path without checking to see if it exists.

幽梦紫曦~ 2024-07-16 02:36:04

我建议为此使用正则表达式,因为您特别不想测试路径是否存在。

这是google 帮我挖掘的内容

RegEx="^([a-zA-Z]\:|\\\\[^\/\\:*?"<>|]+\\[^\/\\:*?"<>|]+)(\\[^\/\\:*?"<>|]+)+(\.[^\/\\:*?"<>|]+)$"

您可以将其与 System.IO.Path 结合起来.GetInvalidPathChars() 方法并使正则表达式动态排除所有无效字符。

I'd suggest just using a regex for this since you specifically don't want to test if the path exists.

Here's something google helped me dig up:

RegEx="^([a-zA-Z]\:|\\\\[^\/\\:*?"<>|]+\\[^\/\\:*?"<>|]+)(\\[^\/\\:*?"<>|]+)+(\.[^\/\\:*?"<>|]+)$"

You could combine this with System.IO.Path.GetInvalidPathChars() method and make the regex dynamically exclude all of the invalid characters.

蓝咒 2024-07-16 02:36:04

您也许可以使用 System.IO.Path 和 GetInvalidPathChars() 函数?

You might be able to use System.IO.Path and the GetInvalidPathChars() function?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文