如何用java分割字符串,但也保留分隔符的句子结尾

时间:2011-02-18 10:00:25

标签: java

  

可能重复:
  Is there a way to split strings with String.split() and include the delimiters?

假设我有以下句子 -

What is your name? My name is Don. You are so nice!

我希望java的输出如下

What is your name?
My name is Don.
You are so nice!

我使用了java split()方法。但它在没有分隔符的情况下分裂。我用split("[\\.!?]")

2 个答案:

答案 0 :(得分:0)

这就是诀窍:

split("(?<=[.?!])");

(改编自this great answer

答案 1 :(得分:0)

你应该在空白上拆分,并在'。!?'上查看字符。

String s = "What is your name? My name is Don. You are so nice!";

String[] tokens = s.split("(?<=[\\.\\!\\?])\\s");

for (String t : tokens) System.out.println(t);