java - 使用正则表达式解析句子,包括 java 中的项目符号列表

标签 java regex

目前,我使用以下正则表达式来解析文档中的句子:

Pattern.compile("(?<=\\w[\\w\\)\\]](?<!Mrs?|Dr|Rev|Mr|Ms|vs|abd|ABD|Abd|resp|St|wt)[\\.\\?\\!\\:\\@]\\s)");

这几乎行得通。例如:给定这个字符串:

“玛丽有一只小羊羔(即羊羔派)。这是它的特性: 1. 它有四只脚 2. 它有羊毛 3. 它是哺乳动物。它有白色的羊毛。她的父亲,羔羊先生,住在 Mulbery St. 的一栋白色小房子里。”

我得到以下句子:

Mary had a little lamb (i.e. lamby pie).
Here are its properties: 
1. It has four feet  2. It has fleece 3. It is a mammal. 
It had white fleese. 
Her father, Mr. Lamb, live on Mulbery St. in a little white house.

但是,我想要的是:

Mary had a little lamb (i.e. lamby pie).
Here are its properties: 
1. It has four feet  
2. It has fleece 
3. It is a mammal. 
It had white fleese. 
Her father, Mr. Lamb, lives on Mulbery St. in a little white house.

有没有办法通过改变现有的正则表达式来做到这一点?

现在为了完成这项任务,我首先进行初始拆分,然后检查子弹。以下代码有效,但我想知道是否有更优雅的解决方案:

public static void doHomeMadeSentenceParser(String temp) {
    Pattern p = Pattern
            .compile("(?<=\\w[\\w\\)\\]](?<!Mrs?|Dr|Rev|Mr|Ms|vs|abd|ABD|Abd|resp|St|wt)[\\.\\?\\!\\:\\@]\\s)");
    String[] sentences = p.split(temp);
    Vector psentences = new Vector();
    Pattern p1 = Pattern.compile("\\b\\d+[.)]\\s");
    for (int x = 0; x < sentences.length; x++) {
        Matcher matcher = p1.matcher(sentences[x]);
        int bstart = 0;
        boolean bulletfound = false;
        while (matcher.find()) {
            bulletfound = true;
            String bullet = sentences[x].substring(bstart, matcher.start());
            if (bullet.length() > 0) {
                psentences.add(bullet);
            }
            bstart = matcher.start();
        }
        if (bulletfound)
            psentences.add(sentences[x].substring(bstart));
        else
            psentences.add(sentences[x]);
    }
    for (int x = 0; x < psentences.size(); x++) {
        String s = (String) psentences.get(x);
        System.out.println(s.trim());
    }
}

在此先感谢您的帮助。

埃利奥特

最佳答案

我假设您正在使用正则表达式来查找拆分行的位置。我不知道这个的正则表达式,但你能看一下后跟句点 (.) 的数字吗?

关于java - 使用正则表达式解析句子,包括 java 中的项目符号列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10368090/

相关文章:

java - 如何从 HashMap<String,List<E>> 获取 List<E>

java - 在 JUnit 4.11 中找不到类

regex - 如何否定正则表达式中的字符串

sql-server - 检查 T-SQL 中字符串的起始字符是否按字母顺序排列

java - 将 GET 响应从 restTemplate 转换为自定义类

Java - StackExchange 获取 JSON

java - 更新 map

php - 正则表达式 - 在特定字符的每个实例之后获取所有字符

c# - 在解析为XElement之前如何替换字符串中的所有&,<,>?

java - 用反斜杠替换全部