2014-12-02 95 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

相关问题