我正在將應用程序從PHP遷移到Java,并且在代碼中大量使用了正則表達式。我遇到了PHP中似乎沒有Java等效項的某些問題:preg_replace_callback()對于正則表達式中的每個匹配項,它都會調用一個函數,該函數將匹配文本作為參數傳遞給該函數。用法示例:$articleText = preg_replace_callback("/\[thumb(\d+)\]/",'thumbReplace', $articleText);# ...function thumbReplace($matches) { global $photos; return "<img src=\"thumbs/" . $photos[$matches[1]] . "\">";}用Java做到這一點的理想方法是什么?
3 回答

慕虎7371278
TA貢獻1802條經驗 獲得超4個贊
當您可以在循環中僅使用appendReplacement()和appendTail()時,嘗試模擬PHP的回調功能似乎需要進行大量工作:
StringBuffer resultString = new StringBuffer();
Pattern regex = Pattern.compile("regex");
Matcher regexMatcher = regex.matcher(subjectString);
while (regexMatcher.find()) {
// You can vary the replacement text for each match on-the-fly
regexMatcher.appendReplacement(resultString, "replacement");
}
regexMatcher.appendTail(resultString);
添加回答
舉報
0/150
提交
取消