[Solved] Replace multiple substrings between delimiters in Java


From comment:

but if I do not know the text between the delimiters?

So it sounds like the replacement values are positional.

Best way to do this is a regular expression appendReplacement loop:

public static String replace(String input, String... values) {
    StringBuffer buf = new StringBuffer();
    Matcher m = Pattern.compile("\\|{2}(.*?)\\|{2}").matcher(input);
    for (int i = 0; m.find(); i++)
        m.appendReplacement(buf, (i < values.length ? values[i] : m.group(1)));
    return m.appendTail(buf).toString();
}

Test

String toConvert = "I ||am|| a ||small|| string.";
System.out.println(replace(toConvert, "could be")); // "small" is retained without markers
System.out.println(replace(toConvert, "could be", "bigger"));
System.out.println(replace(toConvert, "could be", "bigger", "better")); // "better" is ignored

Output

I could be a small string.
I could be a bigger string.
I could be a bigger string.

solved Replace multiple substrings between delimiters in Java