I have the following code:
HashMap<String, String> hm = new HashMap<String, String>();
hm.put("title", "testTitle");
hm.put("year", "testYear");
String s = "<title> - <year>";
String result = s.replaceAll("<([^>]*)>", hm.get("$1"));
The problem is when I execute it, it returns me this exception:
Exception in thread “main” java.lang.NullPointerException at
java.util.regex.Matcher.appendReplacement(Unknown Source) at
java.util.regex.Matcher.replaceAll(Unknown Source) at
java.lang.String.replaceAll(Unknown Source)
I don’t understand why, because when executed alone, hm.get(“title”) does work, so why with replaceAll it is not?
Thanks in advance.
Consider the following line:
hm.get("$1")gets executed (and returnsnullsince presumably there’s no entry inhmwith the key equal to"$1").s.replaceAll("<([^>]*)>", null)is called and triggers the NPE.One way to do what you’re trying to do is to use a
Matcherand a loop.