繁体   English   中英

正则表达式将字符串分成句子

[英]Regex To Split String Into Sentences

我需要拆分包含句子的字符串,例如:

"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." 这不是我想要的。

正则表达式通常不能解决这个问题。

你需要一个句子检测算法, OpenNLP有一个

它很简单,可以使用:

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

并处理了许多棘手的案件

  • “Walter White Jr.有钱”
  • “粉红先生不给出提示”

通过嵌套的lookbehinds。

只需根据以下正则表达式拆分输入字符串即可。 下面的正则表达式将根据刚好存在于点之后的边界分割输入字符串,并检查点的前一个字符。 只有当dot的前一个字符不是一个超级字母时,它才会分裂。

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.]

说明:

  • (?<=(?<![AZ])\\\\.)匹配刚刚存在于dot之后的边界,但点之前不会是大写字母。

我试过这个

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));
        }
    }
}

out put是

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM