如何解决Java按名称替换大括号中的单词
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
中键的等效值?
解决方法
可能您正在寻找:
String s = "I bought {0,number,integer} mangos. From {1},the fruit seller. Out of them {2,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<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
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。