2014-10-06 12 views
2

我想搜索包含在${...}中的字符串,並將這些字符串用作HashMap的鍵,該字符串包含我想用於替換${...}的值。如何使用字符串替換的反向引用作爲Java中的HashMap的關鍵字?

在下面的例子中,字符串Master_${field1}_${field2}_End應轉變爲Master_slave1_slave2_End

package com.stackoverflow; 

import java.util.HashMap; 
import java.util.Map; 

public class RegExReplace { 

    public static void main(String[] args) { 
//  String string = "Master_${field1}_${field2}_${nonexisting}_End"; 
     String string = "Master_${field1}_${field2}_End"; 
     Map<String, String> toBeInserted = new HashMap<String, String>(); 
     toBeInserted.put("field1", "slave1"); 
     toBeInserted.put("field2", "slave2"); 
     toBeInserted.put("field3", "slave3"); 

     String pattern = "\\$\\{([a-zA-Z0-9\\-_]*)\\}"; 
     String replace = "$1"; 

//  System.out.println(string.replaceAll(pattern, replace)); 
     System.out.println(string.replaceAll(pattern, toBeInserted.get(replace))); 

    } // END: main() 

} // END: class 

(如何)是否有可能,使用反向引用作爲HashMap中的關鍵字?

+0

您可以創建另一個字符串:'String mapKey = string.replaceAll(pattern,「$ 1」)''然後在第二個替換中使用'mapKey' – BackSlash 2014-10-06 08:07:32

回答

3

可以使用迭代超過您PatternStringBuffer追加更換比賽,因爲這樣的:

String string = "Master_${field1}_${field2}_End"; 
Map<String, String> toBeInserted = new HashMap<String, String>(); 
toBeInserted.put("field1", "slave1"); 
toBeInserted.put("field2", "slave2"); 
toBeInserted.put("field3", "slave3"); 

Pattern p = Pattern.compile("\\$\\{(.+?)\\}"); 
Matcher m = p.matcher(string); 
StringBuffer sb = new StringBuffer(); 
while (m.find()) { 
    String key = m.group(1); 
    if (key != null) { 
     String value = toBeInserted.get(key); 
     if (value != null) 
      m.appendReplacement(sb, value); 
    } 
} 
m.appendTail(sb); 
System.out.println(sb.toString()); 

輸出

Master_slave1_slave2_End 
2

你在正確的軌道上,你的正則表達式看起來不錯。

現在接下來的步驟是:

  1. 編譯字符串正則表達式來進行Pattern對象
  2. 在你的字符串輸入傳遞給編譯Pattern對象(即Matcher matcher = pattern.matcher(stringInput)
  3. 運行一個while (matcher.find()) {...}創建Matcher實例循環
  4. 內循環訪問matcher.group(1)(即反向引用)作爲您的的關鍵

把它完全:

Pattern p = Pattern.compile(pattern); 
Matcher m = p.matcher(string); 
StringBuffer sb = new StringBuffer(); 
while(m.find()) { 
    m.appendReplacement(sb, toBeInserted.get(m.group(1))); 
} 
m.appendTail(sb); 

System.out.println("Converted string is: " + sb.toString()); 
相關問題