我想从String获取一个提取。提取应包含关键字前面的2个单词和关键字后面的2个单词。如果这两个单词不存在,那么句子就应该结束。
示例:
我正在寻找的单词是“example”。
现有字符串:
String text1 = "This is an example.";
String text2 = "This is another example, but this time the sentence is longer";
结果:
text1
应如下所示:
就是一个例子。
text2
应如下所示:
是另一个例子,但是这个
我该怎么做?
答案 0 :(得分:1)
尝试使用Pattern:
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));
}
}
输出:
你可能需要稍微更改正则表达式,但你可以试试这个。是一个例子
是另一个例子,但是这个
答案 1 :(得分:0)
使用replaceAll()
,您可以在一行中执行此操作:
String target = text1.replaceAll(".*?((\\w+\\W+){2})(example)((\\W+\\w+){2})?.*", "$1$3$4");
fyi,\w
表示"字符" \W
表示"非单词字符"