c# - 用引号解析命令行参数
问题描述
好的,所以我用空格吐出命令行参数,比如命令提示符,但问题是,如果用户尝试输入 DoStuff“有空格但被引用的参数”,它将无法正确拆分。我正在使用控制台应用程序。我试过这样做:baseCommand 是用户输入未解析的字符串,而 secondCommand 应该是第二个参数。
int firstQuoteIndex = baseCommand.IndexOf('"');
if (firstQuoteIndex != -1)
{
int secondQuoteIndex = baseCommand.LastIndexOf('"');
secondCommand = baseCommand.Substring(firstQuoteIndex,
secondQuoteIndex - firstQuoteIndex + 1).Replace("\"", "");
}
这很好用,但首先,它很乱,其次,如果用户输入如下内容,我不确定如何执行此操作:
DoSomething "second arg that has spaces" "third arg that has spaces"
请记住,如果 arg(s) 没有引号,则用户不必输入引号。有人有什么建议吗,谢谢。
解决方案
您可以为此目的使用以下正则表达式。
[\""].+?[\""]|[^ ]+
例如,
var commandList = Regex.Matches(baseCommand, @"[\""].+?[\""]|[^ ]+")
.Cast<Match>()
.Select(x => x.Value.Trim('"'))
.ToList();
样本 1 输入
DoSomething "second arg that has spaces" thirdArgumentWithoutSpaces
输出
Command List
------------
DoSomething
second arg that has spaces
thirdArgumentWithoutSpaces
样本 2 输入
DoSomething "second arg that has spaces" "third Argument With Spaces"
输出
Command List
------------
DoSomething
second arg that has spaces
third Argument With Spaces
推荐阅读
- html - 将代码从 ASP 转换为 ASP.NET
- mysql - 未定义变量:mysql whereNotIn
- python - 如何在 python 3 中删除此警告
- rest - Spring Boot Rest 服务下载包含多个文件的 zip 文件
- mysql - 如何在 Xampp 3.2.2(最新版本)中将我的 MySQL 版本升级到 5.7.7 或更高版本,Laravel MySQL 迁移中的错误
- sql-server - 每当 SaleOrderDetail 中的订单项发生更改时,触发器将更改日期和时间放在 Order 表的 LastModified 列中
- javascript - 使用 mustache.js 将数组数据渲染成表格行;坚持实施行编辑
- python - 无限生成器发出的并行异步任务
- asp.net-mvc - 在 MVC Core 中使用 TagHelper 链接到页面的指定部分
- javascript - 服务器上的 Javascript 安全性