public static void main(String[] args) {
Map map = new HashMap(2);
map.put("name", "Jame Gosling");
map.put("alias", "Rod Johnson");
String line = "${name} did a great job, so ${alias} did.";
String regex = "\\$\\{[^\\}]+\\}";
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(line);
String g;
while (m.find()) {
g = m.group();
g = g.substring(2, g.length() - 1);
line = m.replaceFirst(map.get(g) + "");
m = p.matcher(line);
}
System.out.println(line);
}
利用分组简化代码:
public static void main(String[] args) {
Map map = new HashMap(2);
map.put("name", "Jame Gosling");
map.put("alias", "Rod Johnson");
String line = "${name} did a great job, so ${alias} did.";
String regex = "\\$\\{([^\\}]+)\\}";
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(line);
String g;
while (m.find()) {
g = m.group(1);
line = m.replaceFirst(map.get(g) + "");
m = p.matcher(line);
}
System.out.println(line);
}
输出:
Jame Gosling did a great job, so Rod Johnson did.
Java 正则去除字符串两头的空格
String username = " Rod johnson ";
//Pattern p = Pattern.compile("^[\\s]+$");
String to = username.replaceAll("^\\s+|\\s+$", "");
System.out.println(to);