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

慕虎7371278
TA貢獻(xiàn)1802條經(jīng)驗(yàn) 獲得超4個(gè)贊
當(dāng)您可以在循環(huán)中僅使用appendReplacement()和appendTail()時(shí),嘗試模擬PHP的回調(diào)功能似乎需要進(jìn)行大量工作:
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);
添加回答
舉報(bào)
0/150
提交
取消