我试图build立一个正则expression式,我可以用它来匹配本地Windowspath或URI 中的所有重复的斜线 ,然后用一个斜线replace它们, 同时保持URIscheme或本地驱动器部分不变 。
这是我正在testing的例子:
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)[:])/+
但是用一个斜杠来replace匹配会将file:///
写入file://
。 除了最后一个案例,似乎是完美的。
我更熟悉PCRE格式,但看看这个:
( # Capture group (?<!\/)\/ # Look for / that does not follow another / # Look for C:/ (?(?<=\b[a-zA-Z]:\/) # if... # then look for any more / to remove | # else # Look for file:/// (?(?<=\bfile:\/) # if... \/\/ # then look for // right after it | # else # Look for http:// or ftp://, etc. (?(?<=:\/) # if [stuff]:/ \/ # then look for / | # else ) ) ) ) \/+ # everything else with / after it
直播: http : //regex101.com/r/hU4yI4
基本上,我正在使用条件语句来查找这些条件 :
If / is preceded by: \b[a-zA-Z]: then / \bfile: then /// \b\w{2,}: then / (basically anything else, like ftp:, https:, etc.)
没有全部的空白,整个小组看起来更像是:
((?<!\/)\/(?(?<=\b[a-zA-Z]:\/)|(?(?<=\bfile:\/)\/\/|(?(?<=:\/)\/|))))\/+
但是我不确定这将如何插入到C#的正则表达式中。 它可能会直接进入,或可能需要一些按摩(这就是为什么我留在代码中的评论,以便于阅读和更多的边缘情况)。