【问题标题】:How to create args[] from string in java [duplicate]如何从java中的字符串创建args [] [重复]
【发布时间】:2014-06-18 23:57:51
【问题描述】:

我需要模拟命令行,因此我需要将字符串更改为 args[],​​就像在 main 方法中运行带参数的程序一样。

我正在使用commons cli,但它没有任何解析方法,它确实需要字符串数组。

我想,我只是使用split,但不幸的是,看看这个问题:

String input = "-command \"This is a long parameter\"";
String args[] = input.split(" ");
//args[0] = -command
//args[1] = "This
//args[2] = is
//etc.

如果你使用这个 -command "This is a long parameter" 作为你的 main 方法的参数,你会得到以下信息:

//args[0] == -command
//args[1] == This is a long parameter

那么有什么建议吗?第二个问题是在 google 上找到这个,因为每个线程都解释了 args[] 是什么,而不是如何从字符串中获取它。

【问题讨论】:

  • 你试过 input.split("\""); 吗?因为 \" 是你的字符串中的分隔符
  • @BhushanKawadkar - 嗯,它可能是正确的方向,但我有两个分隔符 - 第一个是",第二个是` `(空格)...
  • @Keppil - 非常感谢!这正是我想要的。

标签: java command-line command command-line-arguments


【解决方案1】:

您可以使用正则表达式来剪切字符串。

for (String s : "hello \"world this is\" a string"
        .split(" (?=\")|(?<=\")\\s"))
    System.out.println(s);

上面的代码会显示:

hello 
"world this is"
a string

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-12-05
    • 1970-01-01
    • 1970-01-01
    • 2012-12-20
    • 2011-02-26
    • 2012-11-30
    • 2015-05-28
    相关资源
    最近更新 更多