Example usage for java.util.regex Matcher appendReplacement

List of usage examples for java.util.regex Matcher appendReplacement

Introduction

In this page you can find the example usage for java.util.regex Matcher appendReplacement.

Prototype

public Matcher appendReplacement(StringBuilder sb, String replacement) 

Source Link

Document

Implements a non-terminal append-and-replace step.

Usage

From source file:com.yukthitech.utils.MessageFormatter.java

/**
 * Replaces the args values in "message" using patterns mentioned below and same will be returned. 
 * //from w  ww.j  a  v a  2s.  co  m
 * {} will match with the current index argument. If index is greater than provided values then <undefined> string will be used.
 * {<idx>} can be used to refer to argument at particular index. Helpful in building messages which uses same argument multiple times.
 * 
 * @param message Message string with expressions
 * @param args Values for expression
 * @return Formatted string
 */
public static String format(String message, Object... args) {
    //when message is null, return null
    if (message == null) {
        return null;
    }

    //when args is null, assume empty values
    if (args == null) {
        args = new Object[0];
    }

    Matcher matcher = PARAM_PATTERN.matcher(message);
    StringBuffer buffer = new StringBuffer();

    int loopIndex = 0;
    int argIndex = 0;
    Object arg = null;

    //loop through pattern matches
    while (matcher.find()) {
        //if index is mentioned in pattern
        if (org.apache.commons.lang3.StringUtils.isNotBlank(matcher.group(1))) {
            argIndex = Integer.parseInt(matcher.group(1));
        }
        //if index is not specified, use current loop index
        else {
            argIndex = loopIndex;
        }

        //if the index is within provided arguments length
        if (argIndex < args.length) {
            arg = args[argIndex];
        }
        //if the index is greater than available values
        else {
            arg = UNDEFINED;
        }

        //if argument value is null
        if (arg == null) {
            arg = "null";
        }

        arg = Matcher.quoteReplacement(arg.toString());

        matcher.appendReplacement(buffer, arg.toString());
        loopIndex++;
    }

    matcher.appendTail(buffer);
    return buffer.toString();
}

From source file:info.magnolia.link.LinkUtil.java

/**
 * Parses provided html and transforms all the links to the magnolia format. Used during storing.
 * @param html html code with links to be converted
 * @return html with changed hrefs/*ww  w  .j  av a  2  s. co m*/
 */
public static String convertAbsoluteLinksToUUIDs(String html) {
    // get all link tags
    Matcher matcher = LINK_OR_IMAGE_PATTERN.matcher(html);
    StringBuffer res = new StringBuffer();
    while (matcher.find()) {
        final String href = matcher.group(4);
        if (!isExternalLinkOrAnchor(href)) {
            try {
                Link link = parseLink(href);
                String linkStr = toPattern(link);
                linkStr = StringUtils.replace(linkStr, "\\", "\\\\");
                linkStr = StringUtils.replace(linkStr, "$", "\\$");
                matcher.appendReplacement(res, "$1" + linkStr + "$5");
            } catch (LinkException e) {
                // this is expected if the link is an absolute path to something else
                // than content stored in the repository
                matcher.appendReplacement(res, "$0");
                log.debug("can't parse link", e);
            }
        } else {
            matcher.appendReplacement(res, "$0");
        }
    }
    matcher.appendTail(res);
    return res.toString();
}

From source file:com.vsct.dt.hesperides.resources.KeyValueValorisation.java

private String replaceWithPattern(final String s, final Pattern p,
        final Function<Matcher, String> replacement) {
    Matcher matcher = p.matcher(s);
    StringBuffer sb = new StringBuffer();
    while (matcher.find()) {
        matcher.appendReplacement(sb, replacement.apply(matcher));
    }/*from   w  ww . j  a v a 2s  . co m*/
    matcher.appendTail(sb);
    return sb.toString();
}

From source file:org.onebusaway.webapp.actions.where.ServiceAlertAction.java

private String htmlify(String content) {

    Pattern p = Pattern.compile("(http://[^\\s]+)");
    Matcher m = p.matcher(content);
    StringBuffer sb = new StringBuffer();
    while (m.find()) {
        m.appendReplacement(sb, "<a href=\"" + m.group(1) + "\">" + m.group(1) + "</a> ");
    }/*w ww.  j ava  2 s  .  c  o m*/
    m.appendTail(sb);

    content = sb.toString();

    content = content.replaceAll("\r\n", "<br/>");
    content = content.replaceAll("\n", "<br/>");

    return content;
}

From source file:br.com.capanema.kers.velocity.util.BuildManagerUtil.java

/**
 * Process a path, and can return a list of path, according to the variable (she will go a list of values).
 * @param path/* w  w  w.j av  a  2  s.  com*/
 * @return
 * @throws Exception 
 */
public static String[] processPathVariables(String path, TemplateDataGroup dataGroup) throws Exception {
    StringBuffer replaceResult = new StringBuffer();

    // ---SEARCH FOR stringUtils
    String regexStringUtils = "\\$\\{stringUtils.*?\\(.*?\\)\\}";

    // Compile regular expression
    Pattern patternStringUtils = Pattern.compile(regexStringUtils);

    // Create Matcher
    Matcher matcherStringUtils = patternStringUtils.matcher(path);

    // Find occurrences
    while (matcherStringUtils.find()) {
        String variable = matcherStringUtils.group();

        // Variables
        HashMap<String, Object> velocityVariables = new HashMap<String, Object>();
        velocityVariables.put("data", dataGroup);

        TemplateEngine templateEngine = VelocityTemplateEngine.getInstance();
        String vmResult = templateEngine.runInLine(variable, velocityVariables);
        matcherStringUtils.appendReplacement(replaceResult, vmResult);
    }

    matcherStringUtils.appendTail(replaceResult);
    path = replaceResult.toString();
    replaceResult = new StringBuffer();

    // ---SEARCH FOR VARIABLE data
    String regexVariable = "\\$\\{.*?\\}";
    Map<String, String[]> mapVariableToDuplicateResult = new HashMap<String, String[]>();

    // Compile regular expression
    Pattern patternVariable = Pattern.compile(regexVariable);

    // Create Matcher
    Matcher matcherVariable = patternVariable.matcher(path);

    // Find occurrences
    while (matcherVariable.find()) {
        String variable = matcherVariable.group();
        variable = variable.replaceAll("\\$\\{", "").replaceAll("\\}", "");
        // variable = variable.substring(2, variable.length()-1); //remove ${ }

        // replace a list of matches
        Map<String, Object> objects = new HashMap<String, Object>();
        objects.put("data.config", dataGroup.getConfig());
        objects.put("data.crud", dataGroup.getCrud());
        objects.put("data.bundle", dataGroup.getBundle());

        String[] values = BuildManagerUtil.readValue(variable, objects);
        if (values.length == 1) { // one value
            matcherVariable.appendReplacement(replaceResult, values[0]);
        } else if (values.length > 1) { // list of values
            mapVariableToDuplicateResult.put(variable, values); // guarda todas as
                                                                // vriaveis do tipo
                                                                // LIST do path
        }
    }
    matcherVariable.appendTail(replaceResult);

    // s  permitido uma vriavel do tipo list no nas vriaveis
    if (mapVariableToDuplicateResult.size() > 1) {
        throw new Exception("Template error: Alone it is permitted one variable of the kind LIST in the paths");
    }

    // return results
    // process list of variables, or return
    if (mapVariableToDuplicateResult.size() == 1) { // rules of the list of
                                                    // values for the variable
                                                    // (existe uma vriavel do
                                                    // tipo list)
        List<String> results = new ArrayList<String>(); // grava os resultados
        for (String variable : mapVariableToDuplicateResult.keySet()) { // loop
                                                                        // nas
                                                                        // variaveis
                                                                        // do tipo
                                                                        // list
                                                                        // (que 
                                                                        // uma s)
            String[] values = mapVariableToDuplicateResult.get(variable); // pega os
                                                                          // valores
                                                                          // vlidos
                                                                          // para a
                                                                          // variavel
                                                                          // do tipo
                                                                          // list
                                                                          // (valores
                                                                          // que
                                                                          // devem
                                                                          // entrar
                                                                          // no
                                                                          // lugar
                                                                          // da
                                                                          // vriavel
                                                                          // list)
            for (String value : values) {
                results.add(replaceResult.toString().replaceAll("\\$\\{" + variable + "\\}", value)); // adiciona
                                                                                                      // um
                                                                                                      // path
                                                                                                      // novo
                                                                                                      // para
                                                                                                      // cada
                                                                                                      // valor
                                                                                                      // que
                                                                                                      // tem
                                                                                                      // que
                                                                                                      // ser
                                                                                                      // substituido
            }
        }

        // transforma o list em array de string
        String[] values = new String[results.size()];
        for (int i = 0; i < results.size(); i++) {
            values[i] = results.get(i).toString();
        }
        return values;
    } else if (mapVariableToDuplicateResult.size() == 0 && !replaceResult.toString().equals("")) { // there
                                                                                                   // is
                                                                                                   // does
                                                                                                   // not
                                                                                                   // list
                                                                                                   // of
                                                                                                   // values,
                                                                                                   // is
                                                                                                   // simple
                                                                                                   // replace
        return new String[] { replaceResult.toString() };
    }

    // no encontrou resultados / not matches found
    return new String[] { path };
}

From source file:nl.ivonet.epub.strategy.epub.CommentRemovalStrategy.java

@Override
public void execute(final Epub epub) {
    LOG.debug("Applying {} on [{}]", getClass().getSimpleName(), epub.getOrigionalFilename());

    final List<Resource> htmlResources = epub.getContents().stream()
            .filter(HtmlCorruptDetectionStrategy::isHtml).collect(Collectors.toList());

    for (final Resource content : htmlResources) {
        try {//from  www.  j ava 2 s.  c o  m
            final String html = IOUtils.toString(content.getReader());
            final Matcher matcher = PAT.matcher(html);
            final StringBuffer sb = new StringBuffer();
            while (matcher.find()) {
                matcher.appendReplacement(sb, "");
            }
            matcher.appendTail(sb);
            content.setData(sb.toString().getBytes());

        } catch (IOException e) {
            epub.addDropout(Dropout.READ_ERROR);
        } catch (IllegalArgumentException e) {
            epub.addDropout(Dropout.KEPBUB);
        }

    }

}

From source file:cc.aileron.dao.db.sql.G2DaoSqlMapImpl.java

/**
 * @param targetClass/*from   w  ww  . ja v a2 s  .  c  o  m*/
 * @return dir
 */
private String getDir(final Class<?> targetClass) {
    final String name = targetClass.getCanonicalName();
    if (name == null) {
        return null;
    }
    final StringBuffer buffer = new StringBuffer();
    final Matcher matcher = pattern.matcher(name);
    while (matcher.find()) {
        matcher.appendReplacement(buffer, "/" + matcher.group(1).toLowerCase());
    }
    return matcher.appendTail(buffer).toString();
}

From source file:ch.ifocusit.livingdoc.plugin.publish.HtmlPostProcessor.java

private String replaceAll(String content, Pattern pattern, Function<MatchResult, String> replacer) {
    StringBuffer replacedContent = new StringBuffer();
    Matcher matcher = pattern.matcher(content);

    while (matcher.find()) {
        matcher.appendReplacement(replacedContent, replacer.apply(matcher.toMatchResult()));
    }//from w w w  .j  av a2s . c o m

    matcher.appendTail(replacedContent);

    return replacedContent.toString();
}

From source file:org.beangle.web.agent.BrowserCategory.java

public String match(String agentString) {
    for (Map.Entry<Pattern, String> entry : versionMap.entrySet()) {
        Matcher m = entry.getKey().matcher(agentString);
        if (m.find()) {
            StringBuffer sb = new StringBuffer();
            m.appendReplacement(sb, entry.getValue());
            sb.delete(0, m.start());/*w  w w . j a v  a2  s .co  m*/
            return sb.toString();
        }
    }
    return null;
}

From source file:com.hexidec.ekit.component.HTMLUtilities.java

private static String convertPointsToCm(String html) {
    StringBuffer sb = new StringBuffer();
    Pattern pTag = Pattern.compile("(<.+?style=\")(.+?)(\".*?>)", Pattern.DOTALL);
    Pattern pNumber = Pattern.compile("\\d+(?:\\.\\d*)");
    Matcher mTag = pTag.matcher(html);
    while (mTag.find()) {
        StringBuilder sbStyle = new StringBuilder(mTag.group(1));
        Map<String, String> mapStyle = DocumentUtil.styleToMap(mTag.group(2));
        for (Map.Entry<String, String> e : mapStyle.entrySet()) {
            String key = e.getKey();
            String value = e.getValue();
            if (pNumber.matcher(value).matches()) {
                value = LengthUnit.convertTo(Float.parseFloat(value), "cm");
            }//from www.  j a va  2s .c  om
            sbStyle.append(key + ": " + value + "; ");
        }
        sbStyle.append(mTag.group(3));
        mTag.appendReplacement(sb, Matcher.quoteReplacement(sbStyle.toString()));
    }
    mTag.appendTail(sb);
    return sb.toString();
}