【发布时间】:2014-07-28 05:20:26
【问题描述】:
我正在尝试构建一个正则表达式,我可以使用它来匹配本地 Windows 路径或 URI 中的所有重复斜杠,然后用单个斜杠替换它们,同时离开URI 方案或本地驱动器部分未更改。
这是我正在测试的示例:
http://www.tempuri.org//path//////to/file.ext
c:/path-to/file.ext
c://path-to/file.ext
http://www.tempuri.org
http://www.tempuri.org//
http://www.tempuri.org///
ftp://www.tempuri.org////
file:///c:/path-to//file.ext
file:////c:/path-to/file.ext
file://///c://path-to/file.ext
这就是我想从这些中得到的:
http://www.tempuri.org/path/to/file.ext
c:/path-to/file.ext
c:/path-to/file.ext
http://www.tempuri.org
http://www.tempuri.org/
http://www.tempuri.org/
ftp://www.tempuri.org/
file:///c:/path-to/file.ext
file:///c:/path-to/file.ext
file:///c:/path-to/file.ext
我得到的最接近的是:
(?<!(file:)|(ftp|gopher|http|https|ldap|mailto|net\.pipe|net\.tcp|news|nntp|telnet|uuid)[:])/+
但是用一个斜杠替换匹配项会将file:/// 变成file://。除了最后一种情况,似乎工作得很好。
【问题讨论】:
-
您需要一次性完成吗?例如,您可以将字符串拆分为一个数组,其中一个是 URI 方案,而其余的路径是另一个?
-
这不是必须,但如果可能的话,一次性完成会更优雅。现在我正在单独处理
file:///案子,但我希望能摆脱它。 -
顺便说一下,+1 用于在您的问题中提供示例代码和预期结果!
-
这是XY Problem。您实际上想做什么,因为您为我们提供的解决方案无法解决您未描述的问题。
标签: .net regex windows path normalization