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

在C#中如何提取路径第二和第三个斜杠间的字符串?能否用正则实现?

方案1:字符串分割实现(推荐,逻辑更直观)

直接将路径按目录分隔符切割为分段数组,取对应索引的分段即可:

using System;

class PathExtractDemo
{
    static void Main()
    {
        string targetPath = @"C:\Users\myUserName\OneDrive\Documents\myDocument\";
        // 按反斜杠分割,同时移除空项规避首尾斜杠导致的空元素
        string[] pathSegments = targetPath.Split('\\', StringSplitOptions.RemoveEmptyEntries);
        
        // 分割后索引0为盘符"C:",索引1为"Users",索引2即为目标字段
        if (pathSegments.Length >= 3)
        {
            string result = pathSegments[2];
            Console.WriteLine(result); // 输出:myUserName
        }
        else
        {
            Console.WriteLine("路径层级不足,无法提取目标内容");
        }
    }
}
方案2:正则表达式实现

如果需要通过正则匹配实现,可以用如下规则捕获目标分段:

using System;
using System.Text.RegularExpressions;

class PathExtractDemo
{
    static void Main()
    {
        string targetPath = @"C:\Users\myUserName\OneDrive\Documents\myDocument\";
        // 正则逻辑:匹配开头到第二个反斜杠的内容,捕获第二个与第三个反斜杠之间的非反斜杠字符
        Match matchResult = Regex.Match(targetPath, @"^[^\\]*\\[^\\]*\\([^\\]*)");
        if (matchResult.Success)
        {
            string result = matchResult.Groups[1].Value;
            Console.WriteLine(result); // 输出:myUserName
        }
        else
        {
            Console.WriteLine("未匹配到目标内容");
        }
    }
}

注意事项

  • 以上方案默认适配Windows反斜杠路径,如需兼容Linux/macOS的正斜杠路径,可将分割符替换为Path.DirectorySeparatorChar,同步调整正则规则适配正反斜杠即可。
  • 日常开发优先选择字符串分割方案,无需掌握正则语法,维护成本更低,性能也足以应对绝大多数场景。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.17 19:36:04