正则表达式找到句子的结尾

Rob*_*itt 5 java regex

我正在制作一个正则表达式来查找文本中句子的结尾.在这里,我假设任何句子都可以以.!?有时虽然有人喜欢两个写!!!!!! 在他们和他们的句子.所以我想替换任何重复的点,感叹号或问号.但我想允许使用'...'.我怎么能包含这个例外?请指教,谢谢!

Pattern p = null;
    try {
    //([!?.] with optional spaces), followed by ([!?.] with optional spaces) repeated 1 or more times
        p = Pattern.compile("([!?.]\\s*)([!?.]\\s*)+");
    }
    catch (PatternSyntaxException pex) {
        pex.printStackTrace();
        System.exit(0);
    }

    //get the matcher
    Matcher m = p.matcher(this.sentence);
    int index = 0;
    while(m.find(index))
    {
        System.out.println(this.sentence);
        System.out.println(p.toString());
        String toReplace = sentence.substring(m.start(), m.end());
        toReplace = toReplace.replaceAll("\\.","\\\\.");
        toReplace =toReplace.replaceAll("\\?","\\\\?");
        String replacement = ""+sentence.charAt(m.start());
        this.sentence = this.sentence.replaceAll(toReplace, replacement);
        System.out.println("");
        index = m.end();
        System.out.println(this.sentence);
    }
Run Code Online (Sandbox Code Playgroud)

dar*_*ioo 2

免责声明:我的回答将偏离主题(不使用正则表达式)。

如果不是太重量级,请尝试使用Apache OpenNLP。NLP 的意思是“自然语言处理”。检查有关检测句子的文档。

相关代码位是:

String sentences[] = sentenceDetector.sentDetect("  First sentence. Second sentence. ");
Run Code Online (Sandbox Code Playgroud)

你会得到一个包含两个的数组Strings。第一个将是“第一句话”,第二个将是“第二句话”。

在使用上述代码行之前还需要编写更多代码,但您已经了解了总体思路。