2014-12-02 94 views
2

我需要包含語句將字符串分割,如:使用正則表達式正則表達式將字符串分割成句子

"this is a sentence. this is another. Rawlings, G. stated foo and bar." 

["this is a sentence.", "this is another.", "Rawlings, G. stated foo and bar."] 

我發現的其他解決方案將第三句分成"Rawlings, G.""stated foo and bar."這不是我想要的。

+0

檢查,如果前一個字符是不是一個大寫字母 – jhamon 2014-12-02 13:35:16

+0

檢查。\。\ S {2} VS \。原因是一段時間後句子以2個空格結束,但G.只有一個空格。 – 2014-12-02 13:39:42

+0

http://docs.oracle.com/javase/7/docs/api/java/text/BreakIterator.html#getSentenceInstance()自Java 1.0以來 – Holger 2014-12-02 13:47:31

回答

1

我想這

import java.text.BreakIterator; 
import java.util.Locale; 

public class StringSplit { 
    public static void main(String args[]) throws Exception { 
     BreakIterator iterator = BreakIterator.getSentenceInstance(Locale.US); 
     String source = "This is a sentence. This is another. Rawlings, G. stated foo and bar."; 
     iterator.setText(source); 
     int start = iterator.first(); 
     for (int end = iterator.next(); 
       end != BreakIterator.DONE; 
       start = end, end = iterator.next()) { 
      System.out.println(source.substring(start, end)); 
     } 
    } 
} 

了賣出期權

This is a sentence. 
This is another. 
Rawlings, G. stated foo and bar. 
3

通過嵌套lookbehinds。

只是根據下面的正則表達式分割你的輸入字符串。下面的正則表達式會根據存在於點後面的邊界來分割輸入字符串,並檢查點的前一個字符。只有當點的前一個字符不是一個大寫字母時,它纔會分裂。

String s = "this is a sentence. this is another. Rawlings, G. stated foo and bar."; 
String[] tok = s.split("(?<=(?<![A-Z])\\.)"); 
System.out.println(Arrays.toString(tok)); 

輸出:

[this is a sentence., this is another., Rawlings, G. stated foo and bar.] 

說明:

  • (?<=(?<![A-Z])\\.)比賽剛剛之後存在的邊界點,但該點不會被大寫字母前面。
+0

你可以添加一行解釋。這將有所幫助 – Backtrack 2014-12-02 13:37:14

6

正則表達式通常不能解決此問題。

你需要一個句子檢測算法,OpenNLP有一個

這是很簡單的使用方法:

String sentences[] = sentenceDetector.sentDetect(yourString); 

,並處理了很多棘手的案件

  • 「沃爾特·白小有錢「
  • 」粉紅先生不給小費「
+2

在爲項目添加第三方庫依賴項之前,總是有必要查看[Java的內置功能](http://docs.oracle.com/javase/7/docs/api/java/text /BreakIterator.html#getSentenceInstance())... – Holger 2014-12-02 13:51:33

+0

不夠公平,但你不能教給breakIterator如何處理某些情況。 – mishadoff 2014-12-02 14:08:55

相關問題