50,541
社区成员
发帖
与我相关
我的任务
分享
//直接replaceAll
String[][] params = {
{"Name1", "Tom"},
...
}
String text = "$Name1$ is a good person. ...";
for (String[] p : params) {
text = text.repalceAll(String.format("$%s$", p[0]), p[1]);
}
System.out.println(text);
//或者正则替换
Map<String, String> params = new HashMap<String, String>();
params.put("Name1", "Tom");
...
String text = "$Name1$ is a good person. ...";
Matcher m = Pattern.compile("[$]([^$]*?)[$]").matcher(text);
StringBuffer buf = new StringBuffer();
while (m.find()) {
m.appendReplacement(buf, params.get(m.group(1)));
}
buf.appendTail();
text = buf.toString();
System.out.println(text);
//保存参数到Map
Map<String, String> params = new HashMap<String, String>();
Scanner sc = new Scanner(new FileInputStream("参数文本文件"));
while (sc.hashNext()) {
String[] sa = sc.nextLine().split("\\s+");
if (sa.length==2) params.put(sa[0], sa[1]);
}
sc.close();
//替换文本并保存结果
sc = new Scanner(new FileInputStream("替换文本文件"));
PrintStream ps = new PrintStream(new FileOutputStream("结果文本文件"));
Pattern p = Pattern.compile("[$]([^$]*?)[$]");
while (sc.hashNext()) {
Matcher m = p.matcher(sc.nextLine());
StringBuffer buf = new StringBuffer();
while (m.find()) { //查找并替换参数
m.appendReplacement(buf, params.get(m.group(1)));
}
buf.appendTail();
ps.println(buf); //替换结果写入结果文件
}
sc.close();
ps.close();