这是一个字符串:
String s = "119 days 6 hours 13 minutes 24 seconds";
如何拆分以获得这样的数组:
{
"119 days",
"6 hours",
"13 minutes",
"24 seconds"
}
我不知道自己怎么做。
我查找了 String.split()
并尝试了 [a-z]\s
regExp,但它删除了最后一个字符
最佳答案
针对此特定情况的一种方法是使用负向回顾 进行拆分。
import java.util.Arrays;
class rTest {
public static void main (String[] args) {
String s = "119 days 6 hours 13 minutes 24 seconds";
String[] parts = s.split("(?<![^a-zA-Z])\\s");
System.out.println(Arrays.toString(parts));
}
}
正则表达式:
(?<! look behind to see if there is not:
[^a-zA-Z] any character except: 'a' to 'z', 'A' to 'Z'
) end of look-behind
\s whitespace (\n, \r, \t, \f, and " ")
输出
[119 days, 6 hours, 13 minutes, 24 seconds]
关于java - 按空格拆分字符串,Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19600876/