在Java中替换分隔符之间的多个子字符串

时间:2018-06-07 00:18:46

标签: java regex

我有以下字符串:

String str1 = "could be";
String str2 = "bigger";

并希望转换此字符串:

String toConvert = "I ||am|| a ||small|| string.";

进入这一个:

"I could be a bigger string."

我怎么能用Java做到这一点?

1 个答案:

答案 0 :(得分:0)

来自comment

  

但如果我不知道分隔符之间的文字?

所以听起来替换值是位置

最好的方法是使用正则表达式appendReplacement循环:

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();
}

测试

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

输出

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