If I got a String
="#1 and #2", a Map
={"1":"a", "2":"b"}, What I indend to do is to replace #x
with the value evaluated from Map(x)
, whose result should be "a and b".
My code is as follows:
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);
}
But the output is infinite like:
1and #2
2and #2
2and #2
2and #2
...
...
Could anyone give me an explanation on this phenomennon, as well as give me a proper solution to my problem? Thanks a lot!