0

Possible Duplicate:
Is there a way to split strings with String.split() and include the delimiters?

Suppose I have the following sentences-

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

I want the output by java as follows

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

I used the java split() method. but it split without the delimiters. i used split("[\\.!?]")

Community
  • 1
  • 1
Shahjalal
  • 1,163
  • 7
  • 21
  • 38
  • 3
    This question is an exact duplicate of http://stackoverflow.com/questions/275768/is-there-a-way-to-split-strings-with-string-split-and-include-the-delimiters -- please remember to search before posted. – Nick Feb 18 '11 at 10:03
  • @Nick, that question asks how to split on non alphanumerics, which is not what the OP wants. – Qwerky Feb 18 '11 at 10:26

2 Answers2

0

This does the trick:

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

(Adapted from this great answer)

Community
  • 1
  • 1
Andreas Dolk
  • 113,398
  • 19
  • 180
  • 268
  • that doesn't remove the space, which I believe the OP wants. – Qwerky Feb 18 '11 at 10:36
  • @Qwerky - The requirement was: split at delimiters (punctuation marks) and keep them. But getting rid of the space(s) in one go, like you showed, is an nice idea (bonus). – Andreas Dolk Feb 18 '11 at 10:41
0

You should split on whitespace, with a lookbehind on the '.!?' characters.

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);
Qwerky
  • 18,217
  • 6
  • 44
  • 80