LoginSignup
0
3

More than 3 years have passed since last update.

Java 文字列 複数置換

Last updated at Posted at 2018-12-18

標準ライブラリ ちょっと煩雑だけど早いかも

    String str = "$aTEST$bTESTTEST$cTESTTEST$aTEST$bTESTTEST$cTESTTEST";
    // 置換前, 置換後
    Map<String, String> map = new HashMap<>();
    map.put("$a", "AaA");
    map.put("$b", "BbB");
    // ・
    // ・
    // 置換処理(java.util.regex.Matcher)
    Matcher matcher = Pattern.compile(map.keySet().stream().map(Pattern::quote).collect(Collectors.joining("|"))).matcher(str);
    StringBuffer sb = new StringBuffer();
    while (matcher.find()) {
        matcher.appendReplacement(sb, map.get(matcher.group()));
    }
    matcher.appendTail(sb);
    sb.toString();

appache commons ライブラリ 簡潔だけど思ったより遅い...

    String str = "$aTEST$bTESTTEST$cTESTTEST$aTEST$bTESTTEST$cTESTTEST";
    // 置換前, 置換後
    Map<String, String> map = new HashMap<>();
    map.put("$a", "AaA");
    map.put("$b", "BbB");
    // ・
    // ・
    // 置換処理(org.apache.commons.lang3.StringUtils)
    StringUtils.replaceEach(str, map.keySet().toArray(new String[map.size()]), map.values().toArray(new String[map.size()]));
0
3
3

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
3