shell - 是否有任何 Dart 资源可以将命令行字符串拆分为列表论据?
问题描述
是否有任何Dart
资源可以将命令行String
拆分List<String>
为参数?
ArgsParser
通常List<String>
从main(List<String>)
.
解决方案
为了回答我自己的问题,
我已经将我喜欢的 Java 函数转换为 DartConverter<String, List<String>)
类:
import 'dart:convert';
/// Splits a `String` into a list of command-line argument parts.
/// e.g. "command -p param" -> ["command", "-p", "param"]
///
class CommandlineConverter extends Converter<String, List<String>>
{
@override
List<String> convert(String input)
{
if (input == null || input.isEmpty)
{
//no command? no string
return [];
}
final List<String> result = new List<String>();
var current = "";
String inQuote;
bool lastTokenHasBeenQuoted = false;
for (int index = 0; index < input.length; index++)
{
final token = input[index];
if (inQuote != null)
{
if (token == inQuote)
{
lastTokenHasBeenQuoted = true;
inQuote = null;
}
else
{
current += token;
}
}
else
{
switch (token)
{
case "'": // '
case '"': // ""
inQuote = token;
continue;
case " ": // space
if (lastTokenHasBeenQuoted || current.isNotEmpty)
{
result.add(current);
current = "";
}
break;
default:
current += token;
lastTokenHasBeenQuoted = false;
}
}
}
if (lastTokenHasBeenQuoted || current.isNotEmpty)
{
result.add(current);
}
if (inQuote != null)
{
throw new Exception("Unbalanced quote $inQuote in input:\n$input");
}
return result;
}
}
推荐阅读
- mysql - Mysql 时差不起作用 MySQL 客户端版本:3.23.49
- c# - 如何从 TextBox 中获取 txt 并将其转换为数学函数?
- css - 如何设置此 div 以显示内联?
- javascript - jQuery - jquery-3.4.1.min.js:2 Uncaught ReferenceError: filter is not defined
- r - 使用 dplyr 语法和 attr 函数转换时区
- html - 为什么锚标记不支持完整性属性,是否有解决方法?
- python - 有没有办法根据 python 中的 excel 中的日期数据类型生成图表?
- javascript - 如何在使用回调方法从firebase中删除数据之前将所有数据插入firebase?
- angularjs - 当我们点击angularjs中的提交按钮时如何动态获取额外的行
- git - 远程分支不在终端中显示?