如何匹配 - 任何事物{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"
在你想捕獲的東西周圍放置圓括號。 – 2014-09-02 16:28:47
考慮發佈示例,它將演示您想要實現的內容。爲了簡化,不要搜索100個字符,而要搜索3-5個字符。此外,「*這件事不起作用*」實際上並沒有描述你的問題,這意味着其他有類似問題的人將無法找到你的問題和答案。 – Pshemo 2014-09-02 16:29:15
你可以發佈樣本數據和你想要的輸出嗎? – 2014-09-02 16:30:33