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

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (60)

有以下字符串:

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

希望转换成以下字符串:

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

输出

"I could be a bigger string."

怎样才能在Java中做到这一点呢?

提问于
用户回答回答于

最佳方法是用一个正则表达式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.
用户回答回答于

用以下代码:

toConvert = toConvert.replaceFirst("\\|\\|[^\\|\\|]+..", str1).replaceFirst("\\|\\|[^\\|\\|]+..", str2);

输出:

I could be a bigger string.

扫码关注云+社区

领取腾讯云代金券