2014-09-02 24 views
0

如何匹配 - 任何事物{100Chars} + MyString +任何事物{100Chars}?我需要保存左右字符串。 這件事情不工作(沒有找到模式字符串是文本,leftContext作爲RightContext爲null):Java正則表達式任何{100} SomethingAnything {100},需要保存左右字符

String text="*SomeText*"; 
String word = hello; 
int nLeft=100; 
int nRight=100; 

String wordDelRegEx = "[^a-zA-Z0-9.-]+?"; 
String leftRegEx = "[\\w]{" + nLeft + "}";  
String rightRegEx = "[\\w]{" + nRight + "}"; 

String contextRe = leftRegEx + wordDelRegEx + word + wordDelRegEx + rightRegEx; 
Pattern pattern = Pattern.compile(contextRe); 
Matcher matcher = pattern.matcher(Text); 
while (matcher.find()) { 
     leftContext = matcher.group(1); 
     rightContext = matcher.group(2); 
    } 

    System.out.println("Left: " + leftContext); 
    System.out.print("Right: " + rightContext); 

比如我有文字:

如果你還沒有找到它但是,繼續尋找。不要解決。如同心中的所有事情一樣,當你找到它時你就會知道。就像任何真誠的關係,只關心

word="heart", nLeft=5, nRight=5 

輸出更好,更好,因爲歲月的流逝我想看看:

Left: " the " 
Right: ", you" 
+2

在你想捕獲的東西周圍放置圓括號。 – 2014-09-02 16:28:47

+1

考慮發佈示例,它將演示您想要實現的內容。爲了簡化,不要搜索100個字符,而要搜索3-5個字符。此外,「*這件事不起作用*」實際上並沒有描述你的問題,這意味着其他有類似問題的人將無法找到你的問題和答案。 – Pshemo 2014-09-02 16:29:15

+0

你可以發佈樣本數據和你想要的輸出嗎? – 2014-09-02 16:30:33

回答

3

添加捕獲括號:

​​
+0

我的匹配器仍然沒有找到它。我編輯了我的問題,希望它有幫助。 – Steve 2014-09-02 19:17:37

+0

錯過了'['和']'在那裏的事實。他們是不必要的。 – 2014-09-02 19:30:41