嘗試使用模式:
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));
}
}
輸出:
就是一個例子
是另外一個例子,但這
mayby你將需要改變正則表達式一點點,但你可以試試這個。
正則表達式或使用'split',[搜索爲索引](http://stackoverflow.com/questions/23160832/how-to-find-index-of-string-array-in-java-from-a-given-value),然後用get打印結果找到索引及其鄰居。 – Tom