2015-06-14 112 views
0

我想從字符串中獲取摘錄。摘錄應包含關鍵字前面的2個字和關鍵字後面的2個字。如果這兩個單詞不存在,該句應該結束。如何獲取字符串中的特定提取?

實施例:

字即時尋找是「榜樣」

現有的字符串:

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

結果:

text1應該是這樣的:

就是一個例子。

text2應該是這樣的:

是另外一個例子,但這

我怎樣才能做到這一點?

+0

正則表達式或使用'split',[搜索爲索引](http://stackoverflow.com/questions/23160832/how-to-find-index-of-string-array-in-java-from-a-given-value),然後用get打印結果找到索引及其鄰居。 – Tom

回答

1

嘗試使用模式:

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你將需要改變正則表達式一點點,但你可以試試這個。

0

使用replaceAll(),你可以做一個行:

String target = text1.replaceAll(".*?((\\w+\\W+){2})(example)((\\W+\\w+){2})?.*", "$1$3$4"); 

僅供參考,\w手段 「單詞字符」 和\W的意思是 「非字字符」

相關問題