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

C# CLI开发:如何拆分含空格的命令行文本为令牌?

处理C# CLI命令行令牌拆分(支持带空格的引号参数)

方案一:轻量正则表达式实现

针对你的场景,不需要额外依赖的话,可以用正则精准匹配命令行令牌——既识别双引号包裹的含空格参数,也兼容普通无引号参数。

核心思路是匹配两种情况:

  • 双引号包裹的内容(忽略内部空格)
  • 非空白的连续字符序列

代码示例:

using System;
using System.Text.RegularExpressions;
using System.Collections.Generic;

class CliParser
{
    static void Main()
    {
        Console.Write("> ");
        string command = Console.ReadLine();
        string[] tokens = ParseCommandTokens(command);

        // 输出测试结果
        Console.WriteLine("拆分后的令牌:");
        for (int i = 0; i < tokens.Length; i++)
        {
            Console.WriteLine($"[{i}]: '{tokens[i]}'");
        }
    }

    static string[] ParseCommandTokens(string command)
    {
        // 正则规则:匹配双引号包裹的内容,或非空白连续字符
        // 若要支持转义引号(如"folder with \"quote\""),可改用: @"\""((?:\\.|[^\""])*)\""|(\S+)"
        Regex tokenRegex = new Regex(@"\""([^\""]*)\""|(\S+)");
        MatchCollection matches = tokenRegex.Matches(command);
        List<string> tokens = new List<string>();

        foreach (Match match in matches)
        {
            // 优先取引号内的内容(捕获组1),否则取非空白序列(捕获组2)
            if (!string.IsNullOrEmpty(match.Groups[1].Value))
            {
                tokens.Add(match.Groups[1].Value);
            }
            else if (!string.IsNullOrEmpty(match.Groups[2].Value))
            {
                tokens.Add(match.Groups[2].Value);
            }
        }

        return tokens.ToArray();
    }
}

测试场景验证:

  • 输入cd some_folder → 得到令牌:["cd", "some_folder"]
  • 输入cd "another folder" → 得到令牌:["cd", "another folder"]
  • 输入echo "hello world" test123 → 得到令牌:["echo", "hello world", "test123"]

方案二:用.NET官方CLI解析库(适合复杂场景)

如果你的CLI应用后续要扩展更多命令(如dir、rm等),推荐使用微软官方的System.CommandLine库——它原生支持带引号的参数处理,还能帮你处理命令、选项、参数的校验和绑定,减少重复造轮子。

步骤如下:

  1. 安装NuGet包:System.CommandLine
  2. 代码示例:
using System;
using System.CommandLine;

class CliApp
{
    static int Main(string[] args)
    {
        // 定义cd命令及其参数
        var cdCommand = new Command("cd", "切换工作目录")
        {
            new Argument<string>("target-path", "要切换到的目录路径")
        };

        // 绑定命令处理逻辑
        cdCommand.SetHandler((targetPath) =>
        {
            Console.WriteLine($"尝试切换到目录:{targetPath}");
            // 这里添加你的目录切换实现逻辑
        }, cdCommand.Arguments[0]);

        // 注册根命令
        var rootCommand = new RootCommand("模拟CLI控制台应用");
        rootCommand.AddCommand(cdCommand);

        // 读取用户输入并解析执行
        Console.Write("> ");
        string input = Console.ReadLine();
        return rootCommand.Invoke(input);
    }
}

这个方案无需自己处理参数拆分,库会自动识别带引号的参数,同时支持命令行的完整语法(如选项、别名等),适合长期维护的项目。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 23:21:34