0
I know this post came from 2010, buat the fact that I just searched for it, may be someone else would still need it too. So here is the function I created for my need.
我知道這篇文章來自2010年,但事實上,我剛剛搜索了它,可能其他人仍然需要它。這是我根據需要創建的函數。
basically, it will replace all keywords with the value from a json (or model, or any data source)
基本上,它將用json(或模型或任何數據源)的值替換所有關鍵字
how to use:
如何使用:
JsonObject jsonROw = some_json_object;
String words = "this is an example. please replace these keywords [id], [name], [address] from database";
String newWords = preg_match_all_in_bracket(words, jsonRow);
I use this codes in my shared adapter.
我在共享適配器中使用這些代碼。
public static String preg_match_all_in_bracket(String logos, JSONObject row) {
String startString="\\[", endString="\\]";
return preg_match_all_in_bracket(logos, row, startString, endString);
}
public static String preg_match_all_in_bracket(String logos, JSONObject row, String startString, String endString) {
String newLogos = logos, withBracket, noBracket, newValue="";
try {
Pattern p = Pattern.compile(startString + "(\\w*)" + endString);
Matcher m = p.matcher(logos);
while(m.find()) {
if(m.groupCount() == 1) {
noBracket = m.group(1);
if(row.has(noBracket)) {
newValue = ifEmptyOrNullDefault(row.getString(noBracket), "");
}
if(isEmptyOrNull(newValue)) {
//no need to replace
} else {
withBracket = startString + noBracket + endString;
newLogos = newLogos.replaceAll(withBracket, newValue);
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
return newLogos;
}
I am also new to Java/Android, please feel free to correct if you think this is a bad implementation or something. tks
我也是Java/Android的新手,如果您認為這是一個不好的實現,請隨意糾正。謝謝大家