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:org.cesecore.config.ConfigurationHolder.java

private static String interpolate(final String orderString) {
    final Pattern PATTERN = Pattern.compile("\\$\\{(.+?)\\}");
    final Matcher m = PATTERN.matcher(orderString);
    final StringBuffer sb = new StringBuffer(orderString.length());
    m.reset();//from w w  w . ja  va 2  s  . c om
    while (m.find()) {
        // when the pattern is ${identifier}, group 0 is 'identifier'
        final String key = m.group(1);
        final String value = getExpandedString(key);

        // if the pattern does exists, replace it by its value
        // otherwise keep the pattern ( it is group(0) )
        if (value != null) {
            m.appendReplacement(sb, value);
        } else {
            // I'm doing this to avoid the backreference problem as there will be a $
            // if I replace directly with the group 0 (which is also a pattern)
            m.appendReplacement(sb, "");
            final String unknown = m.group(0);
            sb.append(unknown);
        }
    }
    m.appendTail(sb);
    return sb.toString();
}

From source file:com.icesoft.faces.webapp.parser.JspPageToDocument.java

static String toSingletonTag(String pattern, String input) {
    Pattern tagPattern = Pattern.compile(pattern, Pattern.DOTALL);
    Matcher tagMatcher = tagPattern.matcher(input);
    StringBuffer tagBuf = new StringBuffer();
    while (tagMatcher.find()) {
        String tagName = tagMatcher.group(1);
        String attributes = tagMatcher.group(2);
        tagMatcher.appendReplacement(tagBuf, escapeBackreference("<" + tagName + attributes + "/>"));
    }/*from   w ww  . j ava  2s .  c o m*/
    tagMatcher.appendTail(tagBuf);
    return tagBuf.toString();
}

From source file:edu.tum.cs.conqat.quamoco.qiesl.QIESLEngine.java

/**
 * Converts expression with model names to expression with technical names.
 * If a model name cannot be resolved a {@link QIESLException} is thrown.
 *///from w w  w  .j  a va  2 s  .co m
protected static String toTechnicalExpression(String expression, Map<String, String> nameMapping)
        throws QIESLException {
    Matcher matcher = PATTERN_FOR_MEASURE_NAMES.matcher(expression);
    StringBuffer result = new StringBuffer();
    while (matcher.find()) {
        String match = matcher.group(1);
        if (!nameMapping.containsValue(match)) {
            throw new QIESLException("Unknown variable '" + match + "' in spec;" + " available names are '"
                    + nameMapping.values() + "'");
        }
        String replacement = toTechnicalName(match);
        matcher.appendReplacement(result, StringUtils.escapeRegexReplacementString(replacement));
    }
    matcher.appendTail(result);
    return result.toString();
}

From source file:info.magnolia.cms.util.LinkUtil.java

/**
 * Convert the mangolia format to absolute (repository friendly) pathes
 * @param str html//from   w ww . j av a 2  s .  co m
 * @return html with absolute links
 */
public static String convertUUIDsToAbsoluteLinks(String str) {
    Matcher matcher = uuidPattern.matcher(str);
    StringBuffer res = new StringBuffer();
    while (matcher.find()) {
        String absolutePath = null;
        String uuid = matcher.group(1);

        if (StringUtils.isNotEmpty(uuid)) {
            absolutePath = LinkUtil.makeAbsolutePathFromUUID(uuid);
        }

        // can't find the uuid
        if (StringUtils.isEmpty(absolutePath)) {
            absolutePath = matcher.group(2);
            log.error("Was not able to get the page by jcr:uuid nor by mgnl:uuid. Will use the saved path {}",
                    absolutePath);
        }
        matcher.appendReplacement(res, absolutePath + ".html"); //$NON-NLS-1$
    }
    matcher.appendTail(res);
    return res.toString();
}

From source file:de.uni.bremen.monty.moco.ast.expression.literal.StringLiteral.java

/** replaces escape sequences of string literals by the LLVM IR equivalents
 *
 * @param value/*www. j av a2 s .c  o  m*/
 *            the string which should be escaped
 * @return an escaped string */
public static String replaceEscapeSequences(String value) {
    // replace escape sequences
    value = value.replace("\\t", "\\09"); // horizontal tab
    value = value.replace("\\b", "\\08"); // backspace
    value = value.replace("\\n", "\\0A"); // line feed
    value = value.replace("\\r", "\\0D"); // carriage return
    value = value.replace("\\f", "\\0C"); // formfeed
    value = value.replace("\\'", "\\27"); // single quote
    value = value.replace("\\\"", "\\22"); // double quote
    value = value.replace("\\\\", "\\5C"); // backslash

    // replace unicode escape sequences by utf-8 codes
    StringBuffer output = new StringBuffer();
    Pattern regex = Pattern.compile("(\\\\u....)|\\P{ASCII}");
    Matcher matcher = regex.matcher(value);
    byte[] utf8;
    while (matcher.find()) {
        String replacement = "";

        if (matcher.group().startsWith("\\u")) {
            // convert hexadecimal unicode number to utf-8 encoded bytes
            utf8 = Character.toString((char) Integer.parseInt(matcher.group().substring(2), 16))
                    .getBytes(StandardCharsets.UTF_8);
        } else {
            // convert a unicode character to utf-8 encoded bytes
            utf8 = matcher.group().getBytes(StandardCharsets.UTF_8);
        }
        // convert utf-8 bytes to hex strings (for LLVM IR)
        for (byte c : utf8) {
            replacement += String.format("\\\\%02x", c);
        }
        matcher.appendReplacement(output, replacement);
    }
    matcher.appendTail(output);

    return output.toString();
}

From source file:org.ballerinalang.auth.ldap.util.LdapUtils.java

/**
 * Replace system property holders in the property values.
 * e.g. Replace ${ballerina.home} with value of the ballerina.home system property.
 *
 * @param value string value to substitute
 * @return String substituted string//from w  w  w .j  a va 2s.  c om
 */
public static String substituteVariables(String value) {
    Matcher matcher = systemVariableIdentifierPattern.matcher(value);
    boolean found = matcher.find();
    if (!found) {
        return value;
    }
    StringBuffer sb = new StringBuffer();
    do {
        String sysPropKey = matcher.group(1);
        String sysPropValue = getSystemVariableValue(sysPropKey, null);
        if (sysPropValue == null || sysPropValue.length() == 0) {
            throw new RuntimeException("System property " + sysPropKey + " is not specified");
        }
        // Due to reported bug under CARBON-14746
        sysPropValue = sysPropValue.replace("\\", "\\\\");
        matcher.appendReplacement(sb, sysPropValue);
    } while (matcher.find());
    matcher.appendTail(sb);
    return sb.toString();
}

From source file:Main.java

public static String unescapeXML(final String xml) {
    Pattern xmlEntityRegex = Pattern.compile("&(#?)([^;]+);");
    //Unfortunately, Matcher requires a StringBuffer instead of a StringBuilder
    StringBuffer unescapedOutput = new StringBuffer(xml.length());

    Matcher m = xmlEntityRegex.matcher(xml);
    Map<String, String> builtinEntities = null;
    String entity;/*from   w ww  .j av a  2s  .c  o m*/
    String hashmark;
    String ent;
    int code;
    while (m.find()) {
        ent = m.group(2);
        hashmark = m.group(1);
        if ((hashmark != null) && (hashmark.length() > 0)) {
            code = Integer.parseInt(ent);
            entity = Character.toString((char) code);
        } else {
            //must be a non-numerical entity
            if (builtinEntities == null) {
                builtinEntities = buildBuiltinXMLEntityMap();
            }
            entity = builtinEntities.get(ent);
            if (entity == null) {
                //not a known entity - ignore it
                entity = "&" + ent + ';';
            }
        }
        m.appendReplacement(unescapedOutput, entity);
    }
    m.appendTail(unescapedOutput);

    return unescapedOutput.toString();
}

From source file:net.sf.sahi.util.Utils.java

@SuppressWarnings("unchecked")
public static String substitute(final String content, final Map substitutions) {

    StringBuffer patternBuf = new StringBuffer();
    int i = 0;//from  w w w. java2  s  . c  om
    Iterator<?> keys = substitutions.keySet().iterator();
    while (keys.hasNext()) {
        String key = (String) keys.next();
        patternBuf.append(i++ == 0 ? "" : "|").append("\\$").append(key);
    }
    Pattern pattern = Pattern.compile(patternBuf.toString());
    patternBuf = null;
    Matcher matcher = pattern.matcher(content);

    StringBuffer buf = new StringBuffer();
    while (matcher.find()) {
        String key = matcher.group(0).substring(1);
        String replaceStr = ((String) substitutions.get(key)).replace("\\", "\\\\").replaceAll("\\$", "SDLR");
        matcher.appendReplacement(buf, replaceStr);
    }
    matcher.appendTail(buf);
    return buf.toString().replaceAll("SDLR", "\\$");
}

From source file:com.amazonaws.util.HttpUtils.java

/**
 * Encode a string for use in the path of a URL; uses URLEncoder.encode,
 * (which encodes a string for use in the query portion of a URL), then
 * applies some postfilters to fix things up per the RFC. Can optionally
 * handle strings which are meant to encode a path (ie include '/'es
 * which should NOT be escaped)./*  w  w  w  . j  a v  a2 s .  co  m*/
 *
 * @param value the value to encode
 * @param path true if the value is intended to represent a path
 * @return the encoded value
 */
public static String urlEncode(final String value, final boolean path) {
    if (value == null) {
        return "";
    }

    try {
        String encoded = URLEncoder.encode(value, DEFAULT_ENCODING);

        Matcher matcher = ENCODED_CHARACTERS_PATTERN.matcher(encoded);
        StringBuffer buffer = new StringBuffer(encoded.length());

        while (matcher.find()) {
            String replacement = matcher.group(0);

            if ("+".equals(replacement)) {
                replacement = "%20";
            } else if ("*".equals(replacement)) {
                replacement = "%2A";
            } else if ("%7E".equals(replacement)) {
                replacement = "~";
            } else if (path && "%2F".equals(replacement)) {
                replacement = "/";
            }

            matcher.appendReplacement(buffer, replacement);
        }

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

    } catch (UnsupportedEncodingException ex) {
        throw new RuntimeException(ex);
    }
}

From source file:org.nuxeo.theme.html.CSSUtils.java

public static String rgbToHex(String value) {
    value = value.replaceAll("\\s", "");
    final Matcher m = rgbDigitPattern.matcher(value);
    final StringBuffer sb = new StringBuffer();
    while (m.find()) {
        final String[] rgb = m.group(1).split(",");
        final StringBuffer hexcolor = new StringBuffer();
        for (String element : rgb) {
            final int val = Integer.parseInt(element);
            if (val < 16) {
                hexcolor.append("0");
            }/*from   ww w.  j  a  v  a  2  s  .c  om*/
            hexcolor.append(Integer.toHexString(val));
        }
        m.appendReplacement(sb, hexcolor.toString());
    }
    m.appendTail(sb);
    return sb.toString();
}