如何用空格分割字符串并在结果中包含空格作为元素?多个空格分割

时间:2015-12-10 07:43:44

标签: java regex string string-split

我用来分割任意数量空白字符串的代码是

String out="SELECT * FROM EMP WHERE EMPID=10";
String array[] = out.split("\\s+");

我希望将“out”字符串中的空格包含在array []对象中,同时使用空格分割。 我想要的输出是:

array[]={"SELECT","[WHITE SPACE]","*","[WHITE SPACE]","FROM","[WHITE SPACE]","EMP","[WHITE SPACE]","WHERE","[WHITE SPACE]","EMPID=10"}

但我得到的输出是:

 array[]={"SELECT","*","FROM","EMP","WHERE","EMPID=10"}

任何帮助将不胜感激

3 个答案:

答案 0 :(得分:5)

由于split接受正则表达式,您可以使用lookarounds

out.split("(?<=\\s)|(?=\\s)");

这将输出:

[SELECT,  , *,  , FROM,  , EMP,  , WHERE,  , EMPID=10]

请注意,分隔符(在您的情况下为空格)包含在结果中。

答案 1 :(得分:3)

尝试将其拆分为:

  String array[] = out.split("(?=\\s)",-1);

代码是:

 public static void main(String[] args) {
    String out="SELECT * FROM EMP WHERE EMPID=10";
    String array[] = out.split("(?=\\s)",-1);

    for (String string : array) {       
    System.out.print(string);
    }
  }

输出:

SELECT * FROM EMP WHERE EMPID=10

答案 2 :(得分:2)

试试这个,

String out="SELECT * FROM EMP WHERE EMPID=10";
    out = out.replaceAll("\\s+", ",[WHITE SPACE],");

    String [] array = out.split(",");

    ArrayList<String> list = new ArrayList<String>();

    for(String str : array){
        list.add(str);
    }
    System.out.println(list);

输出 enter image description here