Java Regex String Replace HTML replaceTags(String payload, Map tags)

Here you can find the source of replaceTags(String payload, Map tags)

Description

Replace @tag@ tokens in payload with values from tags map.

License

Apache License

Parameter

Parameter Description
payload string with tokens to replace
tags map with token/value pairs

Return

String the processed string

Declaration

public static String replaceTags(String payload,
        Map<String, String> tags) 

Method Source Code

//package com.java2s;
/**//from   ww w.j  ava 2 s  .  c o  m
 * Copyright 2011-2013 BBe Consulting GmbH
 *
 * Licensed 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.Map;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main {
    /**
     * Replace @tag@ tokens in payload with values from tags map.
     * 
     * @param payload   string with tokens to replace
     * @param tags      map with token/value pairs
     * @return String the processed string
     */
    public static String replaceTags(String payload,
            Map<String, String> tags) {
        final Pattern p = Pattern.compile("@(\\w+)@");
        final Matcher m = p.matcher(payload);
        String processedPayload = payload;
        boolean result = m.find();
        if (result) {
            final StringBuffer sb = new StringBuffer();
            do {
                m.appendReplacement(sb,
                        tags.containsKey(m.group(1)) ? tags.get(m.group(1))
                                : "");
                result = m.find();
            } while (result);
            m.appendTail(sb);
            processedPayload = sb.toString();
        }
        return processedPayload;
    }
}

Related

  1. removeTags(String string)
  2. replaceHtml(String html)
  3. replaceHtml(String html)
  4. replaceHtmlEntities(final String text)
  5. replaceHtmlEntities(String aText, boolean preserveFormatting)
  6. replaceTags(String str, Map tags)
  7. replaceTagsUnlessAnchorTagFound(String wikiString, String searchPattern, String replacementPattern)