-5

How to split text int array of sentences based on ?, ! and . in Java?

For example I want to store sentences from a string into a oversized array. myArray[0] = 1st sentence, myArray[1] = 2nd sentence and etc/

  • 4
    Is there anything you have done to try to solve this problem? We will be more willing to answer your question if you tell us what you have tried so far. (Helpful links for asking better questions: [ask], [FAQ]) – tckmn Apr 19 '13 at 01:03

2 Answers2

2

You can use String.split(regex) method, like this:

String[] sentendes = text.split("(?<=[.!?])\\s*");

Using lookbehind should help you preserve the punctuation mark after the sentence.

Here is a small demo on ideone.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
1

Try this regex:

String[] myArray = "sentence! sentence. sentence?".split("(<=[\\!\\?\\.])\\s*")

Explanation:

(<=       lookbehind, to preserve punctuation as in @dasblinkenlight's answer
[         start category (which would be !, ?, or .)
\\!\\?\\. punctuation (must be escaped)
]         end category
)         end lookbehind
\\s*      any amount of whitespace
tckmn
  • 57,719
  • 27
  • 114
  • 156