Example usage for java.util.regex Matcher appendTail

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

Introduction

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

Prototype

public StringBuilder appendTail(StringBuilder sb) 

Source Link

Document

Implements a terminal append-and-replace step.

Usage

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 . ja  v a 2s  .co  m
 */
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: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).//from   www.j  av  a  2  s .com
 *
 * @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: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  ww w .ja v a2s  .c o  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:com.manydesigns.elements.fields.TextField.java

public static String highlightLinks(String str) {
    if (str == null) {
        return null;
    }/*  ww  w .  ja v  a  2s . c  om*/
    // Pattern Matching will be case insensitive.
    Matcher linkMatcher = linkPattern.matcher(str);

    boolean linkTrovato = false;
    StringBuffer sb = new StringBuffer();
    while (linkMatcher.find()) {
        String text = shortenEscaped(linkMatcher.group(0), 22);
        if (linkMatcher.group(1).equalsIgnoreCase("www.")) {
            linkMatcher.appendReplacement(sb,
                    "<a href=\"http://" + linkMatcher.group(0) + "\">" + text + "</a>");
        } else {
            linkMatcher.appendReplacement(sb, "<a href=\"" + linkMatcher.group(0) + "\">" + text + "</a>");
        }
        linkTrovato = true;
    }
    if (linkTrovato) {
        linkMatcher.appendTail(sb);
        str = sb.toString();
        linkTrovato = false;
        sb = new StringBuffer();
    }

    //mail
    Matcher emailMatcher = emailPattern.matcher(str);
    while (emailMatcher.find()) {
        emailMatcher.appendReplacement(sb,
                "<a href=\"mailto:" + emailMatcher.group(0) + "\">" + emailMatcher.group(0) + "</a>");
        linkTrovato = true;
    }
    if (linkTrovato) {
        emailMatcher.appendTail(sb);
        str = sb.toString();
    }
    return str;
}

From source file:org.eclipse.scada.utils.str.StringReplacer.java

/**
 * Replace variables in a string/*from ww  w  .  ja va 2 s. c o  m*/
 *
 * @param string
 *            the string to process
 * @param replaceSource
 *            the source of the replacements
 * @param pattern
 *            the pattern for detecting variables
 * @param nested
 *            <code>true</code> if the replacement process should honor
 *            nested replacements
 * @return the replaced string, or <code>null</code> if the input string was
 *         <code>null</code>
 */
public static String replace(final String string, final ReplaceSource replaceSource, final Pattern pattern,
        final boolean nested) {
    if (string == null) {
        return null;
    }

    final Matcher m = pattern.matcher(string);

    boolean result = m.find();
    if (result) {
        final StringBuffer sb = new StringBuffer();
        do {

            final String key;
            if (m.groupCount() > 0) {
                key = m.group(1);
            } else {
                key = null;
            }

            String replacement = replaceSource.replace(m.group(0), key);
            if (replacement == null) {
                m.appendReplacement(sb, "");
            } else {
                replacement = replacement.replace("\\", "\\\\").replace("$", "\\$");
                m.appendReplacement(sb, replacement);
            }

            result = m.find();
        } while (result);
        m.appendTail(sb);

        final String resultString = sb.toString();
        if (nested && !string.equals(resultString)) {
            /*
             * only try again if we should handle nested replacements and if something changed
             */
            return replace(resultString, replaceSource, pattern, true);
        } else {
            return resultString;
        }
    } else {
        return string;
    }
}

From source file:org.nuclos.common2.StringUtils.java

/**
 * Decode a String with "classic java" unicode escape sequences
 * @param s the input string//  www.j a  v  a  2s .  c o m
 * @return the decoded string (or null, if the input was null)
 */
public static String unicodeDecode(String s) {
    if (s == null)
        return null;
    StringBuffer res = new StringBuffer();
    Pattern p = Pattern.compile("\\\\u\\p{XDigit}{4}");
    Matcher m = p.matcher(s);
    while (m.find()) {
        int v = Integer.parseInt(m.group().substring(2), 16);
        m.appendReplacement(res, Character.toString((char) v));
    }
    return m.appendTail(res).toString();
}

From source file:PropertiesHelper.java

/**
 * Adds new properties to an existing set of properties while
 * substituting variables. This function will allow value
 * substitutions based on other property values. Value substitutions
 * may not be nested. A value substitution will be ${property.key},
 * where the dollar-brace and close-brace are being stripped before
 * looking up the value to replace it with. Note that the ${..}
 * combination must be escaped from the shell.
 *
 * @param a is the initial set of known properties (besides System ones)
 * @param b is the set of properties to add to a
 * @return the combined set of properties from a and b.
 *///from   w w w.  ja v  a  2 s.co m
protected static Properties addProperties(Properties a, Properties b) {
    // initial
    Properties result = new Properties(a);
    Properties sys = System.getProperties();
    Pattern pattern = Pattern.compile("\\$\\{[-a-zA-Z0-9._]+\\}");

    for (Enumeration e = b.propertyNames(); e.hasMoreElements();) {
        String key = (String) e.nextElement();
        String value = b.getProperty(key);

        // unparse value ${prop.key} inside braces
        Matcher matcher = pattern.matcher(value);
        StringBuffer sb = new StringBuffer();
        while (matcher.find()) {
            // extract name of properties from braces
            String newKey = value.substring(matcher.start() + 2, matcher.end() - 1);

            // try to find a matching value in result properties
            String newVal = result.getProperty(newKey);

            // if still not found, try system properties
            if (newVal == null) {
                newVal = sys.getProperty(newKey);
            }

            // replace braced string with the actual value or empty string
            matcher.appendReplacement(sb, newVal == null ? "" : newVal);
        }
        matcher.appendTail(sb);
        result.setProperty(key, sb.toString());
    }
    // final
    return result;
}

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

/**
 * Transforms stored magnolia style links to relative links. This is used to display them in the browser
 * @param str html/*from  ww  w  .j  a v  a2s.  c  o  m*/
 * @param page the links are relative to this page
 * @return html with proper links
 */
public static String convertUUIDsToRelativeLinks(String str, Content page) {
    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.warn("Was not able to get the page by jcr:uuid nor by mgnl:uuid. Will use the saved path {}",
                    absolutePath);
        }

        // to relative path
        String relativePath = makeRelativePath(absolutePath, page);
        matcher.appendReplacement(res, relativePath);
    }
    matcher.appendTail(res);
    return res.toString();
}

From source file:org.nuclos.common2.StringUtils.java

/**
 * Replaces all embedded parameters of the form <code>${...}</code>.
 * The replacement string is determined by calling a given transformer.
 * @param s the input string// w  w  w. j a va 2  s  . c om
 * @param t the transformer which maps a parameter to its replacement
 * @return the given string with all parameters replaced
 */
public static String replaceParameters(String s, Transformer<String, String> t) {
    if (s == null) {
        return null;
    }
    StringBuffer sb = new StringBuffer();
    Matcher m = PARAM_PATTERN.matcher(s);
    while (m.find()) {
        String resId = m.group(1);
        String repString = t.transform(resId);
        m.appendReplacement(sb, Matcher.quoteReplacement(repString));
    }
    m.appendTail(sb);
    return sb.toString();
}

From source file:info.schnatterer.nusic.android.util.TextUtil.java

/**
 * Recursively replaces resources such as <code>@string/abc</code> with
 * their localized values from the app's resource strings (e.g.
 * <code>strings.xml</code>) within a <code>source</code> string.
 * /*from w  w  w .jav  a2s .c om*/
 * Also works recursively, that is, when a resource contains another
 * resource that contains another resource, etc.
 * 
 * @param source
 * @return <code>source</code> with replaced resources (if they exist)
 */
public static String replaceResourceStrings(String source) {
    // Recursively resolve strings
    Pattern p = Pattern.compile(REGEX_RESOURCE_STRING);
    Matcher m = p.matcher(source);
    StringBuffer sb = new StringBuffer();
    while (m.find()) {
        String stringFromResources = AbstractApplication.getStringByName(m.group(1));
        if (stringFromResources == null) {
            Log.w(Constants.LOG,
                    "No String resource found for ID \"" + m.group(1) + "\" while inserting resources");
            /*
             * No need to try to load from defaults, android is trying that
             * for us. If we're here, the resource does not exist. Just
             * return its ID.
             */
            stringFromResources = m.group(1);
        }
        m.appendReplacement(sb, // Recurse
                replaceResourceStrings(stringFromResources));
    }
    m.appendTail(sb);
    return sb.toString();
}