使用CommonsCli,如何解析可能发生多次且具有灵活数量值的Option? [英] With CommonsCli, how do I parse an Option which can occur several times and has a flexible number of values?

查看:66
本文介绍了使用CommonsCli,如何解析可能发生多次且具有灵活数量值的Option?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在某些旧代码中,我将diy命令行解析器移植到Apache CommonsCli.

In some legacy code I'm porting a diy-command-line parser to Apache CommonsCli.

我无法破坏以前允许的+记录在案的选项,而其中一个选项给我带来了麻烦:

I can't break previously allowed+documented Options, and one of the Options is giving me trouble:

该选项具有一个或两个参数,并且可以根据需要指定多次.选项:[-option arg1 [arg2]] +

The Option has either one or two args, and can be specified as many times as desired. Option: [-option arg1 [arg2]]+

我希望结果为String [] []如下:

I want the result as String[][] as following:

cli -option a b -option c 应该导致 [[[a,b],[c,]]

cli -option a -option b c 应该导致 [[a,],[b,c]]

我的代码如下:

final CommandLine cmd;
final Options options = new Options()
    .addOption(Option.builder("option").hasArg().hasArgs().build());
cmd = new DefaultParser().parse(options, args);

thatOption = cmd.getOptionValues("option");

但是解析器吐出[a,b,c]

But the parser spits out [a, b, c]

(我查看了cmd.getOptionProperties,这也许是一种使它适应的方法.)

(I looked at cmd.getOptionProperties, and that might be a way to bodge it.)

有没有办法或者我需要继承DefaultParser的子类?

Is there a way or do I need to subclass DefaultParser?

推荐答案

我发现了一种不太优雅的方法,但是除非有人找到更好的方法,否则我会采用这种方法:

I found a way that doesn't feel very elegant, but I'll take it unless someone comes around with a better one:

Option opt上循环:cmd.getOptions(),然后从 opt.getValues()String [] s

Option option = Option.builder("option").hasArg().hasArgs().build();
final Options options = new Options()
    .addOption(option)
    .addOption("dummy", false, "description");
CommandLine cmd = new DefaultParser().parse(options, new String[] {"-option", "a", "b", "-option", "c", "-dummy"});
        
List<String[]> thatOption = new ArrayList<String[]>();
for (Option opt : cmd.getOptions()) {
    LOG.debug("opt: " + opt.getOpt());
    LOG.debug("equals: " + opt.equals(option));
    if (opt.getOpt() == "model") {
        LOG.debug(Arrays.asList(opt.getValues()).toString());
        thatOption.add(opt.getValues());
    }
}
LOG.debug("size: " + thatOption.size());

DEBUG Test :: equals: true
DEBUG Test :: [a, b]
DEBUG Test :: opt: model
DEBUG Test :: equals: true
DEBUG Test :: [c]
DEBUG Test :: opt: dummy
DEBUG Test :: equals: false
DEBUG Test :: size: 2

这篇关于使用CommonsCli,如何解析可能发生多次且具有灵活数量值的Option?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆