8

Please have a look at the following.

String[]sentenceHolder = titleAndBodyContainer.split("\n|\\.(?!\\d)|(?<!\\d)\\.");

This is how I tried to split a paragraph into sentences. But, there is a problem. My paragraph includes dates like Jan. 13, 2014, words like U.S and numbers like 2.2. They all got splitted by the above code. So basically, this code splits lot of 'dots' whether it is a full stop or not.

I tried String[]sentenceHolder = titleAndBodyContainer.split(".\n"); and String[]sentenceHolder = titleAndBodyContainer.split("\\."); as well. All failed.

How can I split a paragraph into sentences "properly"?

halfer
  • 19,824
  • 17
  • 99
  • 186
PeakGen
  • 21,894
  • 86
  • 261
  • 463
  • 2
    Look at using a sentence [BreakIterator](http://docs.oracle.com/javase/tutorial/i18n/text/about.html) – greg-449 Jan 29 '14 at 12:00
  • You can start by defining `properly` in terms that the computer can understand. – Keppil Jan 29 '14 at 12:01
  • http://stackoverflow.com/questions/17654738/regex-split-text-document-into-sentences – StoopidDonut Jan 29 '14 at 12:02
  • This is not a trivial task, phew... E.g. the sentence "In Sweden a common name is Jan. 31, at least, people have this name.", would be virtually impossible to parse, without some kind of context aware parser. (Edit: "Jan" **is** a common christian name in Sweden ;)) – SamWhan Jan 29 '14 at 12:24
  • http://stackoverflow.com/questions/4674850/converting-a-sentence-string-to-a-string-array-of-words-in-java – james.garriss Oct 28 '15 at 15:43

3 Answers3

19

You can try this

String str = "This is how I tried to split a paragraph into a sentence. But, there is a problem. My paragraph includes dates like Jan.13, 2014 , words like U.S and numbers like 2.2. They all got split by the above code.";

Pattern re = Pattern.compile("[^.!?\\s][^.!?]*(?:[.!?](?!['\"]?\\s|$)[^.!?]*)*[.!?]?['\"]?(?=\\s|$)", Pattern.MULTILINE | Pattern.COMMENTS);
Matcher reMatcher = re.matcher(str);
while (reMatcher.find()) {
    System.out.println(reMatcher.group());
}

Output:

This is how I tried to split a paragraph into a sentence.
But, there is a problem.
My paragraph includes dates like Jan.13, 2014 , words like U.S and numbers like 2.2.
They all got split by the above code.
Manfred Radlwimmer
  • 13,257
  • 13
  • 53
  • 62
Ruchira Gayan Ranaweera
  • 34,993
  • 17
  • 75
  • 115
1
String[] sentenceHolder = titleAndBodyContainer.split("(?i)(?<=[.?!])\\S+(?=[a-z])");

Try this it worked for me.

Manfred Radlwimmer
  • 13,257
  • 13
  • 53
  • 62
Sathesh
  • 39
  • 1
  • 5
0

This will split the paragraph by . ? !:

String a[]=str.split("\\.|\\?|\\!");

You can put any symbol after \\ which you want to use and use | to separate each condition.

Manfred Radlwimmer
  • 13,257
  • 13
  • 53
  • 62