【问题标题】:Replace match with items in order按顺序将匹配项替换为项目
【发布时间】:2021-03-26 08:29:30
【问题描述】:

我在 Java 中有一个字符串,其中包含许多模式。有一个值数组需要根据顺序替换字符串中的每个模式。下面是该方法应该做什么的示例。

public static String replaceValues(String withPattern, String... params){
    Matcher matcher = Pattern.compile("\\{\\}").matcher(withPattern);
    StringBuffer sb = new StringBuffer();
    int index =0;
    while (matcher.find()) {
        if (args.length == index) {
            matcher.appendTail(sb);
            return sb.toString();
        }
        matcher.appendReplacement(sb, params[index]);
        index++;
    }
    return sb.toString();
}
// A quick brown fox jumps over the lazy dog.
replaceValues("A quick brown {} jumps over the lazy {}", "fox", "dog"); 

这行得通。我只是想知道是否有一种更有效的方式来编写这段代码,而不是过于声明。

【问题讨论】:

  • 数组values在哪里定义?

标签: java regex replace


【解决方案1】:

您可以重复使用String#replaceFirst,将每个参数一个接一个地连续替换。

public static String replaceValues(String withPattern, String... params){
    String string = withPattern;
    for (String param: params) {
        string = string.replaceFirst("\\{}", param);
    }
    return string;
}

由于 您可以使用Stream#reduce 方法和withPattern 作为T identity 来实现相同的效果。

public static String replaceValues(String withPattern, String... params){
    return Arrays.stream(params).reduce(
            withPattern, 
            (pattern, param) -> pattern.replaceFirst("\\{}", param));
}

【讨论】:

    【解决方案2】:

    您也可以通过给%s 而不是{} 来欺骗String.format(但如果该方面对您的应用程序至关重要,建议测试性能):

    public static String replaceValues(String withPattern, String... params) {
        return String.format(withPattern.replace("{}", "%s"), (Object[])params);
    }
    

    【讨论】:

    • 参数个数和模式不一样会不会有问题?
    • @Apps 如果值的数量少于占位符的数量,则会出现异常,这是显而易见的。
    • 如果withPattern包含%怎么办?
    【解决方案3】:

    试试这个。

    static final Pattern PAT = Pattern.compile("\\{}");
    
    static String replaceValues(String withPattern, String... parms) {
        Iterator<String> p = List.of(parms).iterator();
        return PAT.matcher(withPattern).replaceAll(m -> p.next());
    }
    
    
    @org.junit.jupiter.api.Test
    void testFormat() {
    System.out.println(replaceValues(
        "A quick brown {} jumps over the lazy {}" , "fox", "dog"));
    

    System.out.println(replaceValues(
        "A quick brown {} jumps over the lazy {}" , "fox", "dog"));
    

    输出

    A quick brown fox jumps over the lazy dog
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-07-31
      • 2019-03-15
      • 2016-06-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-07
      相关资源
      最近更新 更多