我知道这篇文章来自 2010 年,但事实上我只是搜索它,可能其他人也需要它。所以这是我为我的需要创建的函数。
基本上,它会将所有关键字替换为来自 json(或模型,或任何数据源)的值
使用方法:
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);
我在共享适配器中使用此代码。
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;
}
我也是 Java/Android 的新手,如果您认为这是一个糟糕的实现或其他什么,请随时纠正。 tks