Java:当单词之间有可变数量的空格时,按空格分割字符串?
问题描述:
我有以下内容:
String string = "1-50 of 500+";
String[] stringArray = string.split(" ");
打印出这个数组中的所有元素给出了以下内容:
Printing out all the elements in this array gives me the following:
Element 1: 1-50
Element 2: of 500+
如何通过要求单词之间至少有一个空格来分割元素?
How can I get it to split elements by the requirement that there is at least one whitespace between the words?
其他单词,我希望我的元素是:
In other words, I want my elements to be:
Element 1: 1-50
Element 2: of
Element 3: 500+
答
使用 \\\\ +
即使它们更多,也要拆分空格。
Use \\s+
to split on spaces even if they are more.
String string = "1-50 of 500+";
String[] stringArray = string.split("\\s+");
for (String str : stringArray)
{
System.out.println(str);
}
完整示例: http://ideone.com/CFVr6N
编辑:
如果您还要拆分选项卡,请将正则表达式更改为 \\\\ + | \\t +
并且它还检测空格和制表符。
If you also want to split on tabs, change the regex to \\s+|\\t+
and it detects both spaces and tabs as well.