Java 如何按换行符和空格拆分

Java 如何按换行符和空格拆分,java,split,Java,Split,我试着用换行符和空格分开,但没用 String[] parole = stringa.split("\\s\\[\\r\\n]+"); 我觉得你的模式很奇怪\\s匹配所有空格,包括换行符和回车符(以及空格和制表符)。我相信你想要 String stringa = "Like\nthis\ryou see"; String[] parole = stringa.split("\\s+"); System.out.println(Arrays.toString(parole)); 输出为 [Li

我试着用换行符和空格分开,但没用

String[] parole = stringa.split("\\s\\[\\r\\n]+");

我觉得你的模式很奇怪
\\s
匹配所有空格,包括换行符和回车符(以及空格和制表符)。我相信你想要

String stringa = "Like\nthis\ryou see";
String[] parole = stringa.split("\\s+");
System.out.println(Arrays.toString(parole));
输出为

[Like, this, you, see]

它将拆分为任何非字母数字字符

String arr[] = line.split("\\W+");
尽管不建议使用StringTokenizer类,但请尝试使用StringTokenizer类

List<String>  list = new ArrayList<String>();
String message = "This\nis\tthe new beginning of something like that, is it?";
String delim = " \n\r\t";
StringTokenizer st = new StringTokenizer(message,delim);
while (st.hasMoreTokens()) {
    list.add(st.nextToken());
}
System.out.println(list);
List List=new ArrayList();
String message=“这\n是\t类似事情的新开始,是吗?”;
字符串delim=“\n\r\t”;
StringTokenizer st=新的StringTokenizer(消息,delim);
而(st.hasMoreTokens()){
添加(st.nextToken());
}
系统输出打印项次(列表);

您可以在中使用,而不是重新发明轮子。请参阅split、splitByCharacterType和其他“拆分”方法。

定义“不起作用”。向我们展示您的输入、输出和预期输出。这里的
stringa
是什么?预期输出是什么?在
[
可能在s.之后加*左右。像往常一样,Vogella对此有一个非常好的教程。如果你是regex新手,我建议你使用它!你应该在回答中提供足够的信息,即使链接消失,它仍然有用。阅读。重点是。但是如果Apache Commons离线,我们会有更大的担忧。可能,但可能是这样例如,移动到另一个url,而没有将以前的url重定向到新的url。