如何拆分字符串忽略空格?

时间:2016-11-01 23:38:24

标签: java regex string split

我正在尝试将此字符串:"send#hi how are you"拆分为

  1. send
  2. hi how are you
  3. 然后将"hi how are you"拆分为

    1. hi
    2. how
    3. are
    4. you
    5. 我的尝试:

      text[0] = "send#hi how are you";
      String[] one = text[0].split("#");
      String[] two = text[0].split("#")[1].split("\\s#");
      

      分割"send#hi how are you"时,它只会给我"发送"和"嗨" ...

      如何更改代码以使其有效?

3 个答案:

答案 0 :(得分:0)

这里的代码应该有用,假设你不想在英镑符号之前加上这个词:

String x = "send#hi how are you";
x = x.substring(x.indexOf("#")+1, x.length());
String[] splitUp = x.split(" ");

如果你确实想要之前的内容和之后的内容:

String x = "send#hi how are you";
String before = x.substring(0, x.charAt("#"));
String after = x.substring(x.charAt("#")+1, x.length());
String[] splitUp = after.split(" ");

这是另一种做第二种方式:

String x = "send#hi how are you";
String[] pieces = x.split("#");
//at this point pieces[0] will be the word before the pound and pieces[1] what is after
String[] after = pieces[1].split(" ");

最后一个注意事项 - 在" "上拆分是一种方法,但在"\\s"上拆分使用正则表达式基本相同,这可能更可靠。

答案 1 :(得分:0)

您的问题是分割的文本(在这种情况下为"#")被分割消费 - 即它不会保留在任何结果字符串中。

让你前进的最小编辑是改变:

String[] two = text[0].split("#")[1].split("\\s#");

到:

String[] two = text[0].split("#")[1].split("\\s");
//                                             ^--- remove the #

答案 2 :(得分:0)

我会这样做:

import java.util.regex.Matcher;
import java.util.regex.Pattern;

String str = "send#hi how are you";
Pattern p = Pattern.compile("([^#]+)#(.*)");
Matcher m = p.matcher(str);

if (m.find()) {
  String first = m.group(1);
  String[] second = m.group(2).split("\\s+");

  System.out.println(first);
  System.out.println(java.util.Arrays.asList(second));
}

或者如果你想要最简单的方法:

String str = "send#hi how are you";

String[] parts = str.split("#", 2);
String first = parts[0];
String[] second = parts[1].split("\\s+");

System.out.println(first);
System.out.println(Arrays.asList(second));