【问题标题】:splitting whitespaces doesn't work fine分割空格不能正常工作
【发布时间】:2012-05-02 18:09:08
【问题描述】:

我已经搜索了很多关于正则表达式的内容,最后我发现最好使用“\\s+”来分割字符串
但令人惊讶的是它对原始字符串没有任何影响:

private static void process(String command) {
    command = command.substring(0, command.length() - 1);
    String[] splitted = command.split("\\s+");
    for (String str : splitted) {
        System.out.println(str);
    }
}  

样本输入:

Boolean b = new Boolean(true);  

首选输出:

[Boolean,b,=,new,Boolean(true)]  

但我的方法输出是:

Boolean b = new Boolean(true)

【问题讨论】:

  • 你有什么问题?您对该方法的输入、预期输出和实际输出是多少?
  • 如果你想在命令行中解析参数,检查commons.apache.org/cli
  • 我使用子字符串来删除 ';'来自我的字符串
  • @Andrew Thompson:它会删除最后一个字符,但我的问题不存在!
  • -1 关于这个问题。代码和示例输出不匹配。这就是说@Tim Pote 已经给出了你需要的答案。

标签: java regex split whitespace


【解决方案1】:

如果您想要“首选输出”,请使用Arrays.toString(splitted)。但是,您的代码可以正常工作。它在新行上打印数组的每个元素。所以这段代码:

  private static void process(String command) {
    command = command.substring(0, command.length() - 1);

    String[] splitted = command.split("\\s+");

    for (String str : splitted) {
      System.out.println(str);
    }

    System.out.println(Arrays.toString(splitted).replace(" ", ""));
  }

  public static void main(String[] args) {
    process("Boolean b = new Boolean(true); ");
  }

产生这个输出:

Boolean
b
=
new
Boolean(true);
[Boolean, b, =, new, Boolean(true);]

请注意,由于输入字符串中的尾随空格,substring 操作不会像您希望的那样工作。您可以事先使用command.trim() 去掉任何前导/尾随空格。

编辑

我编辑了我的代码,因为正如@Tim Bender 所说,Arrays.toString 的输出中的数组元素之间存在空格,而这并不是 OP 想要的。

【讨论】:

  • 我把你的方法完全替换成了我说的那个,但是输出不是你说的!
  • 将我的 main 方法添加到该类,运行它,然后告诉我你得到了什么。
  • 您可能应该首先发布您的main(或至少它的相关部分)。我们一直都知道您的样本输入和输出已关闭。继续发帖,我去看看。
猜你喜欢
  • 2023-03-28
  • 1970-01-01
  • 1970-01-01
  • 2021-12-06
  • 1970-01-01
  • 1970-01-01
  • 2023-04-08
  • 1970-01-01
  • 2013-03-30
相关资源
最近更新 更多