我有一个段落文本。我想提取两三个包含关键字的句子,在java中使用正则表达式
示例: 段落: ....我的名字是汤姆。我和家人住在乡下。我喜欢这种动物。所以我有一只狗和一只猫。不过,我们吃得很多……
关键字:一只狗和一只猫
期望的结果:我喜欢这只动物。所以我有一只狗和一只猫。不过我们吃得很多
注意:我在java中使用正则表达式。
String line = ".My name is Tom. I live with my family in the countryside. I love the animal. So I have a dog and a cat. However, we eat a lot...... "
String pattern = "a dog and a cat";
Pattern r = Pattern.compile(pattern);
Matcher m = r.matcher(line);
boolean value= false;
if (m.find( )) {
System.out.println(m.toMatchResult());
System.out.println(m.groupCount());
System.out.println(m.group());
} else {
System.out.println("False");
}
最佳答案
这是您想要的模式:
\.([^.]+\.[^.]*a dog and a cat[^.]*\.[^.]+)
由于您使用的是 Java,因此在将其编码为字符串时请记住将反斜杠加倍。
基本上,它会匹配一个文字点,然后匹配任何不是点的字符串(第一个句子),另一个文字点,包含文字的中间句子,然后是另一个不是点的字符序列't a dot(第三句)。
关于java - 如何在java中使用正则表达式提取段落中的句子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40054122/