2011-12-13 18 views
2

我有以下代碼:的replaceAll,正則表達式和HashMap還給我一個NullPointerException

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")); 

問題是,當我執行它,它返回我此異常:在線程

異常「主「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)

我不明白爲什麼,因爲當單獨執行時,hm.get(「title」)確實有效,那麼爲什麼用replaceAll它不是?

在此先感謝。

回答

3

考慮以下行:

String result = s.replaceAll("<([^>]*)>", hm.get("$1")); 
  1. 首先,hm.get("$1")被執行(並返回null因爲大概有一個在hm沒有條目與鍵等於"$1")。
  2. 第二,s.replaceAll("<([^>]*)>", null)被調用並觸發NPE。

你要做的一種方法是使用Matcher和一個循環。

+0

謝謝您的回答,這似乎是做到這一點的最好辦法! – evuez 2011-12-14 18:15:04

1

重新檢查你的語法。閱讀「評估訂單」。

hm.get("$1") 

將尋找一個哈希表項與關鍵正是$1」。哪些不存在,所以你回來null。正則表達式在這一點上還沒有被應用,並且沒有任何聲明可以替代組$1

String result = s.replaceAll("<([^>]*)>", hm.get("$1")); 

等同於:

String nulLValue = hm.get("$1"); // Note: $1 is not substituted. 
String result = s.replaceAll("<([^>]*)>", nullValue); 

看一看涉及Pattern和相關Matcher S中的各種Java的例子。

1

下可能不完美或最佳的,在一些角落情況下可能會失敗,但它與你的榜樣工程:

HashMap<String, String> hm = new HashMap<String, String>(); 
hm.put("title", "testTitle"); 
hm.put("year", "testYear"); 

String s = "<title> - <year>"; 

Scanner scan = new Scanner(s); 
scan.useDelimiter("<|>"); 
while (scan.hasNext()) { 
    final String token = scan.next(); 
    final String value = hm.get(token); 
    if (value != null) { 
     s = s.replace("<" + token + ">", value); 
    } 
} 

System.out.println(s); 
相關問題