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.ibm.jaggr.core.impl.transport.RequestedModuleNames.java

/**
 *  Decode JSON object encoded for url transport.
 *  Enforces ordering of object keys and mangles JSON format to prevent encoding of frequently used characters.
 *  Assumes that keynames and values are valid filenames, and do not contain illegal filename chars.
 *  See http://www.w3.org/Addressing/rfc1738.txt for small set of safe chars.
 *
 * @param encstr/*from  w ww.  j  a v  a2s  .  com*/
 *            the encoded module name list
 * @return the decoded string as a JSON object
 *
 * @throws IOException
 * @throws JSONException
 */
protected JSONObject decodeModules(String encstr) throws IOException, JSONException {
    final String sourceMethod = "decodeModules"; //$NON-NLS-1$
    JSONObject result = null;
    if (isTraceLogging) {
        log.entering(RequestedModuleNames.class.getName(), sourceMethod, new Object[] { encstr });
    }
    if (encstr.length() == 0) {
        result = new JSONObject("{}"); //$NON-NLS-1$
    } else {
        StringBuffer json = new StringBuffer(encstr.length() * 2);
        Matcher m = DECODE_JSON.matcher(encstr);
        while (m.find()) {
            String match = m.group(1);
            if (match.equals("!")) //$NON-NLS-1$
                m.appendReplacement(json, ":"); //$NON-NLS-1$
            else if (match.equals("(")) //$NON-NLS-1$
                m.appendReplacement(json, "{"); //$NON-NLS-1$
            else if (match.equals(")")) //$NON-NLS-1$
                m.appendReplacement(json, "}"); //$NON-NLS-1$
            else if (match.equals("|")) //$NON-NLS-1$
                m.appendReplacement(json, "!"); //$NON-NLS-1$
            else if (match.equals("*")) //$NON-NLS-1$
                m.appendReplacement(json, ","); //$NON-NLS-1$
            else if (match.equals("<")) //$NON-NLS-1$
                m.appendReplacement(json, "("); //$NON-NLS-1$
            else if (match.equals(">")) //$NON-NLS-1$
                m.appendReplacement(json, ")"); //$NON-NLS-1$
        }
        m.appendTail(json);
        String jsonstr = json.toString();
        jsonstr = REQUOTE_JSON.matcher(jsonstr).replaceAll("$1\"$2\"$3"); // matches all keys //$NON-NLS-1$
        jsonstr = REQUOTE_JSON.matcher(jsonstr).replaceAll("$1\"$2\"$3"); // matches all values //$NON-NLS-1$
        result = new JSONObject(jsonstr);
    }
    if (isTraceLogging) {
        log.exiting(RequestedModuleNames.class.getName(), sourceMethod, result);
    }
    return result;
}

From source file:org.echocat.jomon.resources.optimizing.MakeCssResourcePathAbsoluteOptimizer.java

@Nonnull
protected String handleCssBody(@Nonnull String oldCssBody, @Nonnull String uri,
        @Nonnull OptimizationContext context) throws Exception {
    final Matcher matcher = PATTERN.matcher(oldCssBody);
    final StringBuffer sb = new StringBuffer();
    while (matcher.find()) {
        final String oldMatch = matcher.group();
        final String oldUri = matcher.group(3) != null ? matcher.group(3) : matcher.group(2);
        final String uriContent = matcher.group(1) != null ? matcher.group(1) : oldUri;

        final String newUri = newUri(uri, oldUri, context);
        if (newUri != null && !oldUri.equals(newUri)) {
            final String newReplacement = Matcher.quoteReplacement(oldMatch.replace(uriContent, newUri));
            matcher.appendReplacement(sb, newReplacement);
        }/*from   w w w  .j a  v  a2s . co m*/
    }
    matcher.appendTail(sb);
    return sb.toString();
}

From source file:com.g_node.gca.abstracts.AbstractContentTabFragment.java

private void fetchAndUpdateAuthorsDataFromDB() {

    //Query for getting author name, email, position, affiliation data for the particular Abstract
    String authorSQLQuery = "SELECT DISTINCT AUTHORS_DETAILS.AUTHOR_FIRST_NAME, "
            + "AUTHOR_MIDDLE_NAME, AUTHOR_LAST_NAME, AUTHOR_EMAIL, "
            + "ABSTRACT_AUTHOR_POSITION_AFFILIATION.AUTHOR_AFFILIATION, "
            + "ABSTRACT_AUTHOR_POSITION_AFFILIATION.AUTHOR_POSITION "
            + "FROM AUTHORS_DETAILS JOIN ABSTRACT_AUTHOR_POSITION_AFFILIATION USING (AUTHOR_UUID) "
            + "WHERE AUTHORS_DETAILS.AUTHOR_UUID IN "
            + "(SELECT AUTHOR_UUID FROM ABSTRACT_AUTHOR_POSITION_AFFILIATION WHERE ABSTRACT_UUID = '" + value
            + "') " + "AND ABSTRACT_AUTHOR_POSITION_AFFILIATION.AUTHOR_POSITION IN "
            + "(SELECT AUTHOR_POSITION FROM ABSTRACT_AUTHOR_POSITION_AFFILIATION WHERE ABSTRACT_UUID = '"
            + value + "') " + "ORDER BY AUTHOR_POSITION ASC;";

    cursor = DatabaseHelper.database.rawQuery(authorSQLQuery, null);
    Log.i(gtag, "Auth executed query: rows = " + cursor.getCount());

    List<String> abstractAuthorNames = new ArrayList<String>();

    if (cursor != null && cursor.moveToFirst()) {
        do {// w w w . j  av a2 s . c  om
            Log.i(gtag, "in DO WHILE");
            String authEmail = cursor.getString(cursor.getColumnIndexOrThrow("AUTHOR_EMAIL"));
            Log.i(gtag, "author email => " + authEmail);
            String authorName = cursor.getString(cursor.getColumnIndexOrThrow("AUTHOR_FIRST_NAME")) + " "
                    + cursor.getString(cursor.getColumnIndexOrThrow("AUTHOR_LAST_NAME"));
            String authAffiliation = cursor.getString(cursor.getColumnIndexOrThrow("AUTHOR_AFFILIATION"));

            //remove unwanted characters from affiliation superscript id's
            String authAffiliationINTs = authAffiliation.replaceAll("[^0-9][,]", "");

            //pattern to get the digits so to increment those by one later so affiliation numbering starts from 1 instead of 0 
            Pattern digitPattern = Pattern.compile("(\\d)"); // EDIT: Increment each digit.

            Matcher matcher = digitPattern.matcher(authAffiliationINTs);
            StringBuffer result = new StringBuffer();
            while (matcher.find()) {
                matcher.appendReplacement(result, String.valueOf(Integer.parseInt(matcher.group(1)) + 1));
            }
            matcher.appendTail(result);
            authAffiliation = result.toString();

            if (abstractAuthorNames.indexOf(authorName) == -1) {
                abstractAuthorNames.add(authorName);

                if (authEmail == null || authEmail.equals("null")) {
                    Log.i(gtag, "in author check - IF NULL");
                    authorNames.append(Html.fromHtml(
                            "<b>" + authorName + "</b><sup><small>" + authAffiliation + "</small></sup><br/>"));

                } else {
                    Log.i(gtag, "in author check - ELSE ");
                    //authorNames.append(Html.fromHtml("<b><a href=\"mailto:" + authEmail + "\">" + authorName + "</a>"  + "</b><sup><small>"
                    //        + authAffiliation + "</small></sup><br/>"));
                    //authorNames.setMovementMethod(LinkMovementMethod.getInstance());
                    authorNames.append(Html.fromHtml(
                            "<b>" + authorName + "</b><sup><small>" + authAffiliation + "</small></sup><br/>"));
                }
            } else {
                ;
            }

        } while (cursor.moveToNext());
    }

}

From source file:Repackage.java

public StringBuffer repackage(StringBuffer sb) {
    StringBuffer result = null;//w  ww. j a  v  a2 s . c o m

    for (int i = 0; i < _fromMatchers.length; i++) {
        Matcher m = (Matcher) _fromMatchers[i];

        m.reset(sb);

        for (boolean found = m.find(); found; found = m.find()) {
            if (result == null)
                result = new StringBuffer();

            m.appendReplacement(result, _toPackageNames[i]);
        }

        if (result != null) {
            m.appendTail(result);
            sb = result;
            result = null;
        }
    }

    return sb;
}

From source file:com.gargoylesoftware.htmlunit.javascript.IEConditionalCompilationScriptPreProcessor.java

private String replaceCustomCompilationVariables(final String body) {
    final Matcher m = CC_VARIABLE_PATTERN.matcher(body);
    final StringBuffer sb = new StringBuffer();
    while (m.find()) {
        final String match = m.group();
        String toReplace;//from   ww w.j  a  v  a 2 s.  c  o m
        if (match.startsWith("@")) {
            toReplace = replaceOneCustomCompilationVariable(match);
        } else {
            toReplace = match;
        }
        toReplace = StringUtils.sanitizeForAppendReplacement(toReplace);
        m.appendReplacement(sb, toReplace);
    }
    m.appendTail(sb);
    return sb.toString();
}

From source file:com.gargoylesoftware.htmlunit.javascript.IEConditionalCompilationScriptPreProcessor.java

String replaceCompilationVariables(final String source, final BrowserVersion browserVersion) {
    final Matcher m = C_VARIABLE_PATTERN.matcher(source);
    final StringBuffer sb = new StringBuffer();
    while (m.find()) {
        final String match = m.group();
        String toReplace;/*from  ww  w  . j  av  a2s .c  om*/
        if (match.startsWith("@")) {
            toReplace = replaceOneVariable(match, browserVersion);
        } else {
            toReplace = match;
        }
        toReplace = StringUtils.sanitizeForAppendReplacement(toReplace);
        m.appendReplacement(sb, toReplace);
    }
    m.appendTail(sb);
    return sb.toString();
}

From source file:com.haulmont.cuba.gui.components.filter.edit.CustomConditionFrame.java

protected String replaceParamWithQuestionMark(String where) {
    String res = StringUtils.trim(where);
    if (!StringUtils.isBlank(res)) {
        Matcher matcher = QueryParserRegex.PARAM_PATTERN.matcher(res);
        StringBuffer sb = new StringBuffer();
        while (matcher.find()) {
            if (!matcher.group().startsWith(":session$"))
                matcher.appendReplacement(sb, "?");
        }//from  w  w  w. ja  va 2 s  . c  om
        matcher.appendTail(sb);
        return sb.toString();
    }
    return res;
}

From source file:com.google.livingstories.servlet.DataImportServlet.java

private String doMatch(String content, Pattern pattern) {
    Matcher matcher = pattern.matcher(content);
    StringBuffer sb = new StringBuffer();
    while (matcher.find()) {
        String id = matcher.group(2);
        if (contentMap.containsKey(id)) {
            matcher.appendReplacement(sb, "$1" + contentMap.get(id).getId());
        } else {// ww w . j  a  va2 s .  co m
            matcher.appendReplacement(sb, "$0");
        }
    }
    matcher.appendTail(sb);
    return sb.toString();
}

From source file:org.ejbca.core.model.ra.UsernameGenerator.java

/**
 * Interpolate the patterns that exists on the input on the form '${pattern}'.
 * @param input the input content to be interpolated
 * @return the interpolated content//from ww  w  .j a  v  a2  s.  c  om
 */
private String interpolate(String input) {
    if (input == null) {
        return null;
    }
    final Matcher m = PATTERN.matcher(input);
    final StringBuffer sb = new StringBuffer(input.length());
    while (m.find()) {
        // when the pattern is ${identifier}, group 0 is 'identifier'
        String key = m.group(1);
        String value = null;
        if (StringUtils.equals(key, "RANDOM")) {
            value = getRandomString(params.getRandomPrefixLength());
        }
        // 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, "");
            String unknown = m.group(0);
            sb.append(unknown);
        }
    }
    m.appendTail(sb);
    return sb.toString();
}

From source file:com.comphenix.xp.messages.MessageFormatter.java

/**
 * Replaces parameters in the text with their respective value.
 * @param message - message to format./*from   w w  w  .j  a va 2s  . c o  m*/
 * @return Message with every parameter replaced with the corresponding value.
 */
public String formatMessage(String message) {

    if (message == null)
        return null;

    Map<String, ResourceHolder> lookup = getResultMapping();

    StringBuffer output = new StringBuffer();
    Matcher matcher = parameterPattern.matcher(message);

    // Simple variables
    // TODO: Add more variables.
    String sourceText = source != null ? source.getDisplayName() : "Unknown";
    String countText = count != null ? count.toString() : "N/A";

    while (matcher.find()) {

        String enumed = Utility.getEnumName(matcher.group());

        // Replace parameters
        if (enumed.equals("PLAYER"))
            matcher.appendReplacement(output, sourceText);
        else if (enumed.equals("COUNT"))
            matcher.appendReplacement(output, countText);
        else if (lookup.containsKey(enumed))
            matcher.appendReplacement(output, lookup.get(enumed).toString());
        else
            matcher.appendReplacement(output, "{CANNOT FIND " + matcher.group() + "}");
    }

    // Remember color
    matcher.appendTail(output);
    return formatUnescape(formatColor(output));
}