如果我得到String
= “#1和#2”,则Map
= {“1”:“a”,“2”:“b “},我要做的是将#x
替换为Map(x)
评估的值,其结果应为”a和b“。
我的代码如下:
Map<String, String> map = new HashMap<String, String>();
map.put("1", "a");
map.put("2", "b");
String s = "#1 and #2";
Pattern p = Pattern.compile("#(.*?)(\\s|$)");
Matcher m = p.matcher(s);
while(m.find()) {
s = m.replaceFirst(m.group(1));
System.out.println(s);
}
但是输出是无限的:
1and #2
2and #2
2and #2
2and #2
...
...
有人能给我一个关于这个现象的解释,并给我一个正确的解决方案吗?非常感谢!
答案 0 :(得分:1)
将正则表达式模式更改为#(\d+)
以简化。
示例代码1:(使用String#replaceAll())
Map<String, String> map = new HashMap<String, String>();
map.put("1", "a");
map.put("2", "b");
String s = "#1 and #2";
Pattern p = Pattern.compile("#(\\d+)");
Matcher m = p.matcher(s);
while (m.find()) {
String match = m.group(1);
s = s.replaceAll("#"+match, map.get(match));
}
System.out.println(s);
示例代码2:(使用Matcher#appendReplacement())
Map<String, String> map = new HashMap<String, String>();
map.put("1", "a");
map.put("2", "b");
String s = "#1 and #2";
Pattern p = Pattern.compile("#(\\d+)");
Matcher m = p.matcher(s);
StringBuffer buffer = new StringBuffer();
while (m.find()) {
m.appendReplacement(buffer, map.get(m.group(1)));
}
System.out.println(buffer);
请查看Matcher
's documentation,其中详细介绍了更多内容。
帖子Java Regex Replace with Capturing Group可能会帮助您更好地理解它。
答案 1 :(得分:0)
Map<String, String> map = new HashMap<String, String>();
map.put("1", "a");
map.put("2", "b");
String s = "#1 and #2";
String result = null ;
Pattern p = Pattern.compile("#(\\d+).*#(\\d)");
Matcher m = p.matcher(s);
if(m.find()){
result = s.replaceFirst("#\\d+", map.get(m.group(1)));
result = result.replaceFirst("#\\d+", map.get(m.group(2)));
}
System.out.println(result);