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.blockfreie.element.hydrogen.murikate.ApplicationUtil.java

/**
 * Expands expression of the form. ${evn:NAME} expands to the evniroment
 * variable $NAME ${prop:NAME} expands to the property $NAME
 * //  ww w  . j  a  va  2  s  .co  m
 * seen as a replacement of the java.text.MessageFormat
 * 
 * @param value
 *            to be expanded
 * @return the expanded string
 */
public static String elExpand(String value) {
    StringBuffer buffer = new StringBuffer();
    Matcher matcher = EL_PATTERN.matcher(value);
    while (matcher.find()) {
        String prelude = matcher.group(1);
        String name = matcher.group(2);
        String replacement;
        if (EL_ENV_KEY.equals(prelude)) {
            replacement = System.getenv().get(name);
        } else if (EL_PROP_KEY.equals(prelude)) {
            replacement = System.getProperty(name);
        } else {
            replacement = matcher.group();
            LOGGER.log(Level.WARNING, String.format("Unknown expansion : '%s' : ignoring", replacement));
        }
        replacement = replacement.replaceAll("\\$", "\\\\\\$"); // 1. fix $
        // bug with replacement - Illegal groupreference
        matcher.appendReplacement(buffer, replacement);
    }
    matcher.appendTail(buffer);
    return buffer.toString();
}

From source file:com.dtolabs.rundeck.ExpandRunServer.java

/**
 * Return the input with embedded property references expanded
 *
 * @param properties the properties to select form
 * @param input      the input//from   w ww . j a  v a 2  s.c  o  m
 *
 * @return string with references expanded
 */
public static String expandProperties(final Properties properties, final String input) {
    final Pattern pattern = Pattern.compile(PROPERTY_PATTERN);
    final Matcher matcher = pattern.matcher(input);
    final StringBuffer sb = new StringBuffer();
    while (matcher.find()) {
        final String match = matcher.group(1);
        if (null != properties.get(match)) {
            matcher.appendReplacement(sb, Matcher.quoteReplacement(properties.getProperty(match)));
        } else {
            matcher.appendReplacement(sb, Matcher.quoteReplacement(matcher.group(0)));
        }
    }
    matcher.appendTail(sb);
    return sb.toString();
}

From source file:org.openflexo.toolbox.FileUtils.java

/**
 * @param componentName/*from  ww w.j  av  a 2 s .  c  om*/
 * @return
 */
public static String getValidFileName(String fileName) {
    StringBuffer sb = new StringBuffer();
    Matcher m = UNACCEPTABLE_SLASH_PATTERN.matcher(fileName);
    while (m.find()) {
        m.appendReplacement(sb, "/");
    }
    m.appendTail(sb);
    m = UNACCEPTABLE_CHARS_PATTERN.matcher(sb.toString());
    sb = new StringBuffer();
    while (m.find()) {
        m.appendReplacement(sb, "_");
    }
    m.appendTail(sb);
    return sb.toString();
}

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

/**
 * @param input/*from   w  w w . ja v  a 2s  .com*/
 * @return String
 */
public static String transform(String input) {
    String result = input;

    Pattern jspDeclarationPattern = Pattern.compile(JSP_DECL_PATTERN, Pattern.DOTALL);
    Matcher jspDeclarationMatcher = jspDeclarationPattern.matcher(result);
    if (!jspDeclarationMatcher.find()) {
        //no JSP declarations, must be a JSP Document, not a page
        return (preprocessJspDocument(result));
    }

    result = performStaticInclude(STATIC_INCLUDE_PATTERN, input);

    result = toLowerHTML(result);

    Pattern jspTaglibPattern = Pattern.compile(JSP_TAGLIB_PATTERN, Pattern.DOTALL);
    Pattern openTagPattern = Pattern.compile(OPEN_TAG_PATTERN, Pattern.DOTALL);
    Pattern attributePattern = Pattern.compile(ATTRIBUTE_PATTERN, Pattern.DOTALL);
    Pattern prefixPattern = Pattern.compile(PREFIX_PATTERN, Pattern.DOTALL);
    Pattern uriPattern = Pattern.compile(URI_PATTERN, Pattern.DOTALL);

    Hashtable declarationsTable = new Hashtable();
    Matcher jspTaglibMatcher = jspTaglibPattern.matcher(result);
    declarationsTable.put("xmlns:jsp", "jsp");
    declarationsTable.put("xmlns:icefaces", "http://www.icesoft.com/icefaces");

    while (jspTaglibMatcher.find()) {
        String attributes = jspTaglibMatcher.group(1);
        Matcher prefixMatcher = prefixPattern.matcher(attributes);
        Matcher uriMatcher = uriPattern.matcher(attributes);
        prefixMatcher.find();
        uriMatcher.find();
        String prefix = prefixMatcher.group(1);
        String url = uriMatcher.group(1);
        declarationsTable.put("xmlns:" + prefix, url);
    }

    Matcher openTagMatcher = openTagPattern.matcher(result);
    openTagMatcher.find();
    String tag = openTagMatcher.group(1);
    String attributes = openTagMatcher.group(2);

    Matcher attributeMatcher = attributePattern.matcher(attributes);
    while (attributeMatcher.find()) {
        String name = attributeMatcher.group(1);
        String value = attributeMatcher.group(2);
        declarationsTable.put(name, value);
    }

    Enumeration declarations = declarationsTable.keys();
    String namespaceDeclarations = "";
    while (declarations.hasMoreElements()) {
        String prefix = (String) declarations.nextElement();
        String url = (String) declarationsTable.get(prefix);
        namespaceDeclarations += prefix + "=\"" + url + "\" ";
    }

    jspDeclarationMatcher = jspDeclarationPattern.matcher(result);
    result = jspDeclarationMatcher.replaceAll("");

    //ensure single root tag for all JSPs as per bug 361
    result = "<icefaces:root " + namespaceDeclarations + ">" + result + "</icefaces:root>";

    Pattern jspIncludePattern = Pattern.compile(JSP_INCLUDE_PATTERN);
    Matcher jspIncludeMatcher = jspIncludePattern.matcher(result);
    StringBuffer jspIncludeBuf = new StringBuffer();
    while (jspIncludeMatcher.find()) {
        String args = jspIncludeMatcher.group(1);
        jspIncludeMatcher.appendReplacement(jspIncludeBuf,
                "<icefaces:include" + args + " isDynamic=\"#{true}\" />");
    }
    jspIncludeMatcher.appendTail(jspIncludeBuf);
    result = jspIncludeBuf.toString();

    //Fix HTML
    result = toSingletonTag(P_TAG_PATTERN, result);
    result = toSingletonTag(LINK_TAG_PATTERN, result);
    result = toSingletonTag(META_TAG_PATTERN, result);
    result = toSingletonTag(IMG_TAG_PATTERN, result);
    result = toSingletonTag(INPUT_TAG_PATTERN, result);

    Pattern brTagPattern = Pattern.compile(BR_TAG_PATTERN);
    Matcher brTagMatcher = brTagPattern.matcher(result);
    result = brTagMatcher.replaceAll("<br/>");

    Pattern hrTagPattern = Pattern.compile(HR_TAG_PATTERN);
    Matcher hrTagMatcher = hrTagPattern.matcher(result);
    result = hrTagMatcher.replaceAll("<hr/>");

    Pattern nbspEntityPattern = Pattern.compile(NBSP_ENTITY_PATTERN);
    Matcher nbspEntityMatcher = nbspEntityPattern.matcher(result);
    //  result = nbspEntityMatcher.replaceAll("&nbsp;");
    result = nbspEntityMatcher.replaceAll("&amp;nbsp");

    Pattern copyEntityPattern = Pattern.compile(COPY_ENTITY_PATTERN);
    Matcher copyEntityMatcher = copyEntityPattern.matcher(result);
    result = copyEntityMatcher.replaceAll("&#169;");

    Pattern docDeclPattern = Pattern.compile(DOC_DECL_PATTERN);
    Matcher docDeclMatcher = docDeclPattern.matcher(result);
    result = docDeclMatcher.replaceAll("");

    result = unescapeBackslash(result);

    return result;
}

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

/**
 * Decode a String with "classic java" unicode escape sequences
 * @param s the input string//w  ww. j  ava2  s.  c om
 * @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.  j a v  a  2 s  . c o  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.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 ww  .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();
}

From source file:com.thinkbiganalytics.nifi.feedmgr.ConfigurationPropertyReplacer.java

/**
 * @param property         the NifiProperty to replace
 * @param configProperties a Map of properties which will be looked to to match against the property key
 *//*from www.j ava2 s.c o m*/
public static boolean resolveStaticConfigurationProperty(NifiProperty property,
        Map<String, Object> configProperties) {
    String value = property.getValue();
    StringBuffer sb = null;

    if (configProperties != null && !configProperties.isEmpty()) {

        if (StringUtils.isNotBlank(value)) {
            Pattern variablePattern = Pattern.compile("\\$\\{(.*?)\\}");
            Matcher matchVariablePattern = variablePattern.matcher(value);
            while (matchVariablePattern.find()) {
                if (sb == null) {
                    sb = new StringBuffer();
                }
                String group = matchVariablePattern.group();
                int groupCount = matchVariablePattern.groupCount();
                if (groupCount == 1) {

                    String variable = matchVariablePattern.group(1);
                    //lookup the variable
                    //first look at configuration properties
                    Object resolvedValue = configProperties.get(variable);
                    if (resolvedValue != null) {
                        matchVariablePattern.appendReplacement(sb, resolvedValue.toString());
                    }
                }
            }
            if (sb != null) {
                matchVariablePattern.appendTail(sb);
            }
        }
    }

    if (sb == null) {

        String updatedValue = resolveValue(property, configProperties);
        if (StringUtils.isNotBlank(updatedValue)) {
            sb = new StringBuffer();
            sb.append(updatedValue);
        }

    }
    if (sb != null) {
        property.setValue(StringUtils.trim(sb.toString()));
    }

    return sb != null;
}

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/*from   ww  w .j a v a  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.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 av  a  2  s  . 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();
}