亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Java相當于PHP的preg_replace_callback

Java相當于PHP的preg_replace_callback

慕森卡 2019-10-21 15:05:11
我正在將應用程序從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);


查看完整回答
反對 回復 2019-10-21
  • 3 回答
  • 0 關注
  • 1063 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號