有一個業務需求要自己解析替換sql中的參數 網上找了半天倒是有一種方法是遍歷參數的map然后replace之
但是那種方法在參數map數量巨大的時候效率非常之低下 於是我就想能不能用正則表達式來實現
然后就有了下面的代碼
public static void main(String[] args) { String s = "生日:${birthday} 年齡:${age} 性別:${sex}"; Map<String, String> map = new HashMap<String, String>(); map.put("birthday", "19960531"); map.put("age", "22"); map.put("sex", "男"); System.out.println(replaceString(s, map)); } public static String replaceString(String s, Map<String, String> map) { Pattern mPattern = Pattern.compile("\\$\\{(.*?)}"); Matcher mMatcher = mPattern.matcher(s); while (mMatcher.find()) { String find = mMatcher.group(1); s = s.replace(mMatcher.group(0), map.get(find)); } return s; }
關鍵點:
1.正則表達式可以根據自己需求來替換
2.正則表達式中(.*?)中()代表分組 ?代表最短匹配 如果去掉?則按最長匹配就會報錯
3.注意正則表達式中特殊字符比如 $ { 的轉義
4.正則表達式真雞兒麻煩