将 {{xxx}} 替换为 %s

问题描述 投票:0回答:4

如何将下面句子中的

{{......}}
替换为
%s

String str="Your appointment with {{provider_name}} on {{start_time}} is cancelled at {{careCenter_name}}. Call {{careCenter_phoneNumber}} for queries.";

结果应该是这样的:

Your appointment with %s on %s is cancelled at %s. Call %s for queries.";
java string replace
4个回答

0
投票
    String str="Your appointment with {{provider_name}} on {{start_time}} is cancelled at {{careCenter_name}}. Call {{careCenter_phoneNumber}} for queries.";
    String reg="(?:\\{\\{([\\w_-]+)\\}\\})";
    Pattern p = Pattern.compile(reg);
    Matcher m = p.matcher(str);
    while(m.find()){
        str = str.replace(m.group(0), "%s");
    }
    System.out.println(str);

当您想要处理用两个花括号括起来的实际值时,可以使用 m.group(1) 。


0
投票

尝试使用这个正则表达式:-

String s = "Your appointment with {{provider_name}} on {{start_time}}";
s = s.replaceAll("\\{.*?\\}\\}", "%s");

输出:- 您于 %s 与 %s 的约会


0
投票

将此正则表达式与

String.replaceAll()
方法一起使用:

str.replaceAll("\\{\\{.+?\\}\\}", "%s")
© www.soinside.com 2019 - 2024. All rights reserved.