Replace all instances in string with unique replacement

前端 未结 1 933
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-21 20:42

I\'m attempting to replace all instances of a particular String with a unique replacement.

What I would like:

If I have this String:

相关标签:
1条回答
  • 2020-12-21 21:06

    It seems that you are looking for appendReplacement and appendTail methods from Matcher class.

    Both these methods require temporary buffer in which new (replaced) version of string will be placed. In this case StringBuffer is used.

    Their purpose is to add to buffer chunks of modified text

    • appendReplacement(StringBuffer sb, String replacement) when match will be found text from last match (or in case of first match from start of the string) till start of current match + replacement
    • appendTail(StringBuffer sb) when there is no match left, but we also need to add text after last match (or if there was no match entire original string).

    In other words if you have text xxxxfooxxxxxfooxxxx and you want to replace foo to bar matcher will need to invoke

                           xxxxfooxxxxxfooxxxx
    1. appendReplacement   ^^^^^^^              will add to buffer xxxxbar
    1. appendReplacement          ^^^^^^^^      will add to buffer xxxxxbar
    3. appendTail                         ^^^^  will add to buffer xxxx
    

    so after this buffer will contain xxxxbarxxxxxbarxxxx.

    Demo

    String testScript = "while(true) { } while   (10 < 7) { } while((10 < 7)) { }";
    Pattern p = Pattern.compile("while\\s*\\(");
    Matcher m = p.matcher(testScript);
    
    int counter = 0;
    StringBuffer sb = new StringBuffer();
    
    while(m.find()){
        m.appendReplacement(sb, "while(arg"+ (counter++) + " < 5000 && ");
    }
    m.appendTail(sb);
    
    String result = sb.toString();
    System.out.println(result);
    

    Output:

    while(arg0 < 5000 && true) { } while(arg1 < 5000 && 10 < 7) { } while(arg2 < 5000 && (10 < 7)) { }
    
    0 讨论(0)
提交回复
热议问题