C#中使用Regex.Replace移除文件路径前两段的正则表达式需求
C#正则表达式移除UNC路径前两段
正则表达式模式
使用以下正则模式匹配并移除路径开头的前两段(服务器名+第一个文件夹):
^\\\\[^\\]+\\[^\\]+\\
模式说明
^:锚定字符串开头,确保只匹配路径最前端的内容\\\\:匹配UNC路径的起始双反斜杠(C#字符串中需用四个反斜杠转义)[^\\]+:匹配任意非反斜杠字符,分别对应服务器名称和第一个文件夹名称\\:匹配段与段之间的分隔反斜杠
C#代码示例
using System; using System.Text.RegularExpressions; class PathProcessor { static void Main() { string[] originalPaths = { @"\\server\folder\folder1\folder3\someFile.txt", @"\\otherServer\folder123\folder1\folder3\someFile.txt", @"\\serv\fold\folder3\folder4\someFile.txt" }; string regexPattern = @"^\\\\[^\\]+\\[^\\]+\\"; foreach (string path in originalPaths) { string processedPath = Regex.Replace(path, regexPattern, string.Empty); Console.WriteLine(processedPath); } } }
运行结果
folder1\folder3\someFile.txtfolder1\folder3\someFile.txtfolder3\folder4\someFile.txt
内容的提问来源于stack exchange,提问作者Lev Kostychenko
相关产品推荐
相关产品推荐

