You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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.txt
  • folder1\folder3\someFile.txt
  • folder3\folder4\someFile.txt

内容的提问来源于stack exchange,提问作者Lev Kostychenko

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 13:40:35