gpt4 book ai didi

java - 如何从字符串中获取特定的摘录?

转载 作者:行者123 更新时间:2023-12-01 11:25:33 24 4
gpt4 key购买 nike

我想从字符串中获取摘录。摘录应包含关键字前面的 2 个单词和关键字后面的 2 个单词。如果这两个词不存在,则句子应该结束。

示例:

我要找的词是“example”。

现有字符串:

String text1 = "This is an example.";
String text2 = "This is another example, but this time the sentence is longer";

结果:

text1 应如下所示:

is an example.

text2 应如下所示:

is another example, but this

我该怎么做?

最佳答案

尝试使用模式:

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Test {

public static void main(String[] args) {
String text1 = "This is an example.";
String text2 = "This is another example, but this time the sentence is longer";
String key = "example";
String regex = "((\\w+\\s){2})?" + key +"([,](\\s\\w+){0,2})?";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(text1);
matcher.find();
System.out.println(matcher.group(0));
matcher = pattern.matcher(text2);
matcher.find();
System.out.println(matcher.group(0));
}
}

输出:

is an example

is another example, but this

也许您需要稍微更改一下正则表达式,但您可以尝试使用这个。

关于java - 如何从字符串中获取特定的摘录?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30833349/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com