首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >在Java中替换分隔符之间的多个子字符串

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

Stack Overflow用户
提问于 2018-06-07 08:18:46
回答 1查看 71关注 0票数 -6

我有以下字符串:

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

并希望转换此字符串:

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

进入这一步:

"I could be a bigger string."

我如何在Java中做到这一点呢?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-06-07 09:49:24

来自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.
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50731350

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档