[英]Java replace word in curly braces by name
我有一个像这样的字符串:
String message = "This is a message for {ID_PW}. Your result is {exam_result}. Please quote {ID_PW} if replying";
我正在从 CSV 导入数据,我想用它来替换花括号之间的项目。
// Using OpenCSV to read in CSV...code omitted for brevity
values = (Map<String, String>) reader.readMap();
// values has 'ID_PW', 'exam_result', etc keys
如何将message
中花括号中的项目替换为 values 中键的等效values
?
可能您正在寻找:
String s = "I bought {0,number,integer} mangos. From {1}, the fruit seller. Out of them {2,number,percent} were bad.";
MessageFormat formatter = new MessageFormat(s);
Object[] argz = {22, "John", 0.3};
System.out.println(formatter.format(argz));
这输出:
I bought 22 mangos. From John, the fruit seller. Out of them 30% were bad.
有关详细信息,请参阅https://docs.oracle.com/javase/8/docs/api/java/text/MessageFormat.html 。
String message = "This is a message for {ID_PW}. Your result is {exam_result}. Please quote {ID_PW} if replying"; LinkedHashSet<String> fields = new LinkedHashSet<>(); // 'Automatically' handle duplicates Pattern p = Pattern.compile("\\{([^}]*)\\}"); Matcher m = p.matcher(message); // Find 'fields' in the message that are wrapped in curly braces and add to hash set while (m.find()) { fields.add((m.group(1))); } // Go through CSV and parse the message with the associated fields while (((values = (Map<String, String>) reader.readMap())) != null) { Iterator itr = fields.iterator(); String newMsg = message; while (itr.hasNext()) { String field = (String) itr.next(); String value = values.get(field); if(value != null) { newMsg = newMsg.replaceAll("\\{" + field + "\\}", value); } } }
使用StringBuilder
。 StringBuilder
被明确设计为String
的可变类型。 接下来,不要在循环中使用正则表达式。 正则表达式可能很强大,但是由于您将使用循环来搜索多个模式,因此不涉及任何正则(多个模式意味着多个表达式)。
我只需从左到右搜索{
然后}
提取key
并在values
map 中搜索它。 就像是,
Map<String, String> values = new HashMap<>();
values.put("ID_PW", "SimpleOne");
values.put("exam_result", "84");
String message = "This is a message for {ID_PW}. Your result "
+ "is {exam_result}. Please quote {ID_PW} if replying";
StringBuilder sb = new StringBuilder(message);
int p = -1;
while ((p = sb.indexOf("{", p + 1)) > -1) {
int e = sb.indexOf("}", p + 1);
if (e > -1) {
String key = sb.substring(p + 1, e);
if (values.containsKey(key)) {
sb.replace(p, p + key.length() + 2, values.get(key));
}
}
}
System.out.println(sb);
输出
This is a message for SimpleOne. Your result is 84. Please quote SimpleOne if replying
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.