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:Main.java

/**
 * Converts a method name to an attribute name, e.g. getFooBar() --> foo_bar, isFlag --> flag.
 * @param methodName//from  w  w w .  java2s .c  o  m
 * @return
 */
public static String methodNameToAttributeName(final String methodName) {
    String name = methodName;
    if ((methodName.startsWith("get") || methodName.startsWith("set")) && methodName.length() > 3)
        name = methodName.substring(3);
    else if (methodName.startsWith("is") && methodName.length() > 2)
        name = methodName.substring(2);

    // Pattern p=Pattern.compile("[A-Z]+");
    Matcher m = METHOD_NAME_TO_ATTR_NAME_PATTERN.matcher(name);
    StringBuffer sb = new StringBuffer();
    while (m.find()) {
        int start = m.start(), end = m.end();
        String str = name.substring(start, end).toLowerCase();
        if (str.length() > 1) {
            String tmp1 = str.substring(0, str.length() - 1);
            String tmp2 = str.substring(str.length() - 1);
            str = tmp1 + "_" + tmp2;
        }
        if (start == 0) {
            m.appendReplacement(sb, str);
        } else
            m.appendReplacement(sb, "_" + str);
    }
    m.appendTail(sb);
    return sb.length() > 0 ? sb.toString() : methodName;
}

From source file:net.thucydides.core.util.Inflector.java

/**
 * Utility method to replace all occurrences given by the specific backreference with its uppercased form, and remove all
 * other backreferences.//from   w w  w  .  j av a2  s  .co m
 *
 * The Java {@link Pattern regular expression processing} does not use the preprocessing directives <code>\l</code>,
 * <code>&#92;u</code>, <code>\L</code>, and <code>\U</code>. If so, such directives could be used in the replacement string
 * to uppercase or lowercase the backreferences. For example, <code>\L1</code> would lowercase the first backreference, and
 * <code>&#92;u3</code> would uppercase the 3rd backreference.
 *
 * @param input the input string
 * @param regex regular expression to replace
 * @param groupNumberToUppercase the regex group to convert to uppercase
 * @return the input string with the appropriate characters converted to upper-case
 */
private static String replaceAllWithUppercase(String input, String regex, int groupNumberToUppercase) {
    Pattern underscoreAndDotPattern = Pattern.compile(regex);
    Matcher matcher = underscoreAndDotPattern.matcher(input);
    StringBuffer sb = new StringBuffer();
    while (matcher.find()) {
        matcher.appendReplacement(sb, matcher.group(groupNumberToUppercase).toUpperCase());
    }
    matcher.appendTail(sb);
    return sb.toString();
}

From source file:io.wcm.devops.conga.generator.util.VariableStringResolver.java

private static String resolve(String value, Map<String, Object> variables, int iterationCount) {
    if (iterationCount >= REPLACEMENT_MAX_ITERATIONS) {
        throw new IllegalArgumentException("Cyclic dependencies in variable string detected: " + value);
    }//from   ww  w  .  jav  a 2  s.  c  om

    Matcher matcher = VARIABLE_PATTERN.matcher(value);
    StringBuffer sb = new StringBuffer();
    boolean replacedAny = false;
    while (matcher.find()) {
        boolean escapedVariable = StringUtils.equals(matcher.group(1), "\\$");
        String variable = matcher.group(2);
        if (escapedVariable) {
            // keep escaped variables intact
            matcher.appendReplacement(sb, Matcher.quoteReplacement("\\${" + variable + "}"));
        } else {
            Object valueObject = MapExpander.getDeep(variables, variable);
            if (valueObject != null) {
                String variableValue = valueToString(valueObject);
                matcher.appendReplacement(sb, Matcher.quoteReplacement(variableValue.toString()));
                replacedAny = true;
            } else {
                throw new IllegalArgumentException("Unknown variable: " + variable);
            }
        }
    }
    matcher.appendTail(sb);
    if (replacedAny) {
        // try again until all nested references are resolved
        return resolve(sb.toString(), variables, iterationCount + 1);
    } else {
        return sb.toString();
    }
}

From source file:net.sf.jabref.external.RegExpFileSearch.java

/**
 * Takes a string that contains bracketed expression and expands each of these using getFieldAndFormat.
 * <p>/*from   w  w  w .ja v a 2s .c o m*/
 * Unknown Bracket expressions are silently dropped.
 *
 * @param bracketString
 * @param entry
 * @param database
 * @return
 */
public static String expandBrackets(String bracketString, BibEntry entry, BibDatabase database) {
    Matcher m = SQUARE_BRACKETS_PATTERN.matcher(bracketString);
    StringBuffer s = new StringBuffer();
    while (m.find()) {
        String replacement = getFieldAndFormat(m.group(), entry, database);
        m.appendReplacement(s, replacement);
    }
    m.appendTail(s);

    return s.toString();
}

From source file:com.networknt.utility.Util.java

public static String substituteVariables(String template, Map<String, String> variables) {
    Pattern pattern = Pattern.compile("\\$\\{(.+?)\\}");
    Matcher matcher = pattern.matcher(template);
    // StringBuilder cannot be used here because Matcher expects StringBuffer
    StringBuffer buffer = new StringBuffer();
    while (matcher.find()) {
        if (variables.containsKey(matcher.group(1))) {
            String replacement = variables.get(matcher.group(1));
            // quote to work properly with $ and {,} signs
            matcher.appendReplacement(buffer,
                    replacement != null ? Matcher.quoteReplacement(replacement) : "null");
        }/*from  ww  w  .j  a  v  a  2 s .  c om*/
    }
    matcher.appendTail(buffer);
    return buffer.toString();
}

From source file:org.infoscoop.util.I18NUtil.java

private static String replace(String str, Map resMap, boolean onlySystem, boolean escapeXML) {
    StringBuffer sb = new StringBuffer();
    Matcher m = onlySystem ? REPACE_PATTERN2.matcher(str) : REPACE_PATTERN.matcher(str);
    while (m.find()) {
        String g = m.group(1);/*from w  ww  .j ava  2 s. c om*/
        String replacement = (String) resMap.get(g);
        if (replacement == null)
            replacement = g;
        else
            replacement = escapeReplacement(escapeXML ? XmlUtil.escapeXmlEntities(replacement) : replacement);

        m.appendReplacement(sb, replacement);
    }
    m.appendTail(sb);
    return sb.toString();
}

From source file:org.cruk.genologics.api.jaxb.URIAdapter.java

/**
 * Remove any "state=" parameter from the given URI.
 *
 * @param uri The URI to modify.//from   w ww.  j  av  a 2s  .c  om
 *
 * @return A string which is {@code uri} without the state information.
 */
public static String removeStateParameter(String uri) {
    if (uri != null) {
        StringBuffer builder = new StringBuffer();

        Matcher m = STATE_PATTERN.matcher(uri);
        while (m.find()) {
            String replacement = "";

            if (StringUtils.isNotEmpty(m.group(2))) {
                // There are more options after the state parameter.
                // Need to put the first question mark or ampersand back.
                replacement = m.group(1);
            }

            m.appendReplacement(builder, replacement);
        }
        m.appendTail(builder);

        uri = builder.toString();
    }

    return uri;
}

From source file:net.triptech.metahive.CalculationParser.java

/**
 * Marks up the calculation.// w  w  w. j  a  v a2s . co m
 *
 * @param calculation the calculation
 * @return the string
 */
public static String maredUpCalculation(String calculation) {

    String markedUpCalculation = "";

    logger.debug("Calculation: " + calculation);

    if (StringUtils.isNotBlank(calculation)) {
        try {
            Pattern p = Pattern.compile(regEx);
            Matcher m = p.matcher(calculation);
            StringBuffer sb = new StringBuffer();
            logger.debug("Regular expression: " + regEx);
            while (m.find()) {
                logger.info("Variable instance found: " + m.group());
                try {
                    String text = "<span class=\"variable\">" + m.group().toUpperCase() + "</span>";

                    m.appendReplacement(sb, Matcher.quoteReplacement(text));

                } catch (NumberFormatException nfe) {
                    logger.error("Error parsing variable id");
                }
            }
            m.appendTail(sb);

            markedUpCalculation = sb.toString();
            logger.info("Marked up calculation: " + markedUpCalculation);

        } catch (PatternSyntaxException pe) {
            logger.error("Regex syntax error ('" + pe.getPattern() + "') " + pe.getMessage());
        }
    }
    return markedUpCalculation;
}

From source file:Main.java

/**
 * Identify variables in the given string and replace with their values as
 * defined in the variableDefs map.  Variables without definitions are left
 * alone.//from   w ww  .j a va2s.  co m
 *
 * @param string String to do variable replacement in.
 * @param variableDefs Map from variable names to values.
 * @return modified string
 */
public static String replaceVariablesInString(String string, Map<String, String> variableDefs) {

    StringBuffer replacementStringBuffer = new StringBuffer();

    Matcher variableMatcher = variablePattern.matcher(string);
    while (variableMatcher.find()) {
        String varString = variableMatcher.group(1).trim();
        int eqIdx = varString.indexOf("=");

        String varName;
        if (eqIdx > -1)
            varName = varString.substring(0, eqIdx).trim();
        else
            varName = varString;

        String replacementString = variableDefs.containsKey(varName) ? variableDefs.get(varName)
                : variableMatcher.group(0);

        variableMatcher.appendReplacement(replacementStringBuffer, Matcher.quoteReplacement(replacementString));
    }
    variableMatcher.appendTail(replacementStringBuffer);

    return replacementStringBuffer.toString();
}

From source file:com.cognifide.aet.executor.xmlparser.xml.utils.EscapeUtils.java

public static String escapeUrls(String xmlString) {
    Matcher matcher = URL_TAG_PATTERN.matcher(xmlString);
    StringBuffer urlTagStringBuffer = new StringBuffer();
    while (matcher.find()) {
        String attrs = matcher.group(3);
        Matcher attrMatcher = ATTRIBUTES_PATTERN.matcher(attrs);
        StringBuffer attrsStringBuffer = new StringBuffer();
        while (attrMatcher.find()) {
            String attr = attrMatcher.group(1);
            if (attr.startsWith("description=")) {
                validateAttr(attr);//  w  w  w .  j  av a2  s .  c  o m
            }

            if (attr.startsWith("href=")) {
                attr = String.format("href=\"%s\"",
                        StringEscapeUtils.escapeXml11(attr.substring(6, attr.length() - 1)));
            }
            attrMatcher.appendReplacement(attrsStringBuffer, attr + " ");
        }
        attrMatcher.appendTail(attrsStringBuffer);
        String urlString = String.format("<url %s/>", attrsStringBuffer.toString());
        matcher.appendReplacement(urlTagStringBuffer, urlString);
    }
    matcher.appendTail(urlTagStringBuffer);
    return urlTagStringBuffer.toString();
}