Java Regex String Replace replace(String str, String key, String value)

Here you can find the source of replace(String str, String key, String value)

Description

Replace all {key}} in the given string with value .

License

Apache License

Parameter

Parameter Description
str string
key key string
value value to replace key

Return

incoming str with replaced key with given value

Declaration

public static String replace(String str, String key, String value) 

Method Source Code

//package com.java2s;
/*/*from ww  w .  j  a  v a2 s  .  com*/
 * Copyright ? 2016 Oleg Cherednik
 *
 * Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work
 * for additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.  You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations
 * under the License.
 */

import java.util.regex.Pattern;

public class Main {
    private static final Pattern TAG_OPEN = Pattern.compile("\\}");
    private static final Pattern TAG_CLOSE = Pattern.compile("\\{");

    /**
     * Replace all {@code {key}} in the given string with {@code value}.
     * E.g. <i>str=/step/{stepId}/param, key=stepId, value=123</i> then return <i>str=/step/123/param</i>
     *
     * @param str   string
     * @param key   key string
     * @param value value to replace key
     * @return incoming {@code str} with replaced {@code key} with given {@code value}
     */
    public static String replace(String str, String key, String value) {
        return str.replaceAll(TAG_OPEN.matcher(TAG_CLOSE.matcher(key).replaceAll("\\\\{")).replaceAll("\\\\}"),
                value);
    }
}

Related

  1. replace(String s1, String s2, Pattern pattern)
  2. replace(String source, String prefix, String suffix, String prefixReplace, String suffixReplace)
  3. replace(String source, String search, String replace)
  4. replace(String source, String search, String replacement)
  5. replace(String source, String[] patterns, String[] replacements)
  6. replace(String str, String replacement, Function func)
  7. replace(String string, Pattern pattern, String replacement)
  8. replace(String string, Pattern[] patterns, String[] replacements)
  9. replace(String string, Properties table)