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:com.hexidec.ekit.component.HTMLUtilities.java

public static String ensureInlineContent(String s) {
    if (StringUtils.isEmpty(s)) {
        return s;
    }/*from  w w  w .j  a  v  a  2 s . c  om*/
    List<String> inlineTags = ExtendedHTMLDocument.getAcceptedInlineTags();
    StringBuffer sb = new StringBuffer();
    Pattern p = Pattern.compile("</?(\\w+).*?>", Pattern.DOTALL);
    Matcher m = p.matcher(s);
    while (m.find()) {
        String replacement = "";
        if (inlineTags.contains(m.group(1).toLowerCase())) {
            replacement = Matcher.quoteReplacement(m.group());
        }
        m.appendReplacement(sb, replacement);
    }
    m.appendTail(sb);
    return sb.toString();
}

From source file:org.sakaiproject.util.Web.java

/**
 * For converting plain-text URLs in a String to HTML &lt;a&gt; tags
 * Any URLs in the source text that happen to be already in a &lt;a&gt; tag will be unaffected.
 * @param text the plain text to convert
 * @return the full source text with URLs converted to HTML.
 * @deprecated just a copy of {@link org.sakaiproject.util.api.FormattedText#encodeUrlsAsHtml(String)} so use that instead
 *///  ww  w  .  j a v  a2 s.c  om
public static String encodeUrlsAsHtml(String text) {
    Pattern p = Pattern.compile(
            "(?<!href=['\"]{1})(((https?|s?ftp|ftps|file|smb|afp|nfs|(x-)?man|gopher|txmt)://|mailto:)[-:;@a-zA-Z0-9_.,~%+/?=&#]+(?<![.,?:]))");
    Matcher m = p.matcher(text);
    StringBuffer buf = new StringBuffer();
    while (m.find()) {
        String matchedUrl = m.group();
        m.appendReplacement(buf, "<a href=\"" + Web.unEscapeHtml(matchedUrl) + "\">$1</a>");
    }
    m.appendTail(buf);
    return buf.toString();
}

From source file:net.sf.jabref.util.Util.java

/**
 * Takes a string that contains bracketed expression and expands each of these using getFieldAndFormat.
 * <p>/* ww  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 = Util.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:cz.cas.lib.proarc.common.process.GenericExternalProcess.java

/**
 * Interpolate parameter values. The replace pattern is {@code ${name}}.
 * @param s a string to search for placeholders
 * @return the resolved string//from w ww.  j  av a  2  s.  co  m
 * @see #addParameter(java.lang.String, java.lang.String)
 */
static String interpolateParameters(String s, Map<String, String> parameters) {
    if (s == null || s.length() < 4 || parameters.isEmpty()) { // minimal replaceable value ${x}
        return s;
    }
    // finds ${name} patterns
    Matcher m = REPLACE_PARAM_PATTERN.matcher(s);
    StringBuffer sb = null;
    while (m.find()) {
        if (m.groupCount() == 1) {
            String param = m.group(1);
            String replacement = parameters.get(param);
            if (replacement != null) {
                sb = sb != null ? sb : new StringBuffer();
                m.appendReplacement(sb, Matcher.quoteReplacement(replacement));
            }
        }
    }
    if (sb == null) {
        return s;
    }
    m.appendTail(sb);
    return sb.toString();
}

From source file:org.rhq.plugins.jbossas5.util.ResourceComponentUtils.java

/**
 * TODO//from  w  w w.  j  ava  2 s .  co  m
 *
 * @param template
 * @param configuration
 * @return
 */
public static String replacePropertyExpressionsInTemplate(String template, Configuration configuration) {
    if (template == null) {
        return null;
    }
    Pattern propExpressionPattern = Pattern.compile("%[^%]+%");
    Matcher matcher = propExpressionPattern.matcher(template);
    StringBuffer stringBuffer = new StringBuffer();
    while (matcher.find()) {
        // e.g. "%foo%"
        String match = matcher.group();
        // Strip off the percent signs, e.g. "foo".
        String propName = match.substring(1, match.length() - 1);
        PropertySimple prop = configuration.getSimple(propName);
        if (prop == null) {
            LOG.debug("WARNING: Template '" + template + "' references property '" + propName
                    + "' that does not exist in " + configuration.toString(true));
            continue;
        }
        if (prop.getStringValue() != null) {
            matcher.appendReplacement(stringBuffer, prop.getStringValue());
        }
    }
    matcher.appendTail(stringBuffer);
    return stringBuffer.toString();
}

From source file:de.mpg.mpdl.inge.citationmanager.utils.XsltHelper.java

/**
 * Converts snippet &lt;span&gt; tags to the appropriate JasperReport Styled Text. Note: If at
 * least one &lt;span&gt; css class will not match FontStyle css, the snippet will be returned
 * without any changes./*from w w  w  .  j a  v  a  2 s .c o  m*/
 * 
 * @param snippet
 * @return converted snippet
 * @throws CitationStyleManagerException
 */
public static String convertSnippetToJasperStyledText(String cs, String snippet)
        throws CitationStyleManagerException {

    // logger.info("input snippet:" + snippet);

    snippet = removeI18N(snippet);

    FontStylesCollection fsc = XmlHelper.loadFontStylesCollection(cs);

    if (!Utils.checkVal(snippet) || fsc == null)
        return snippet;

    FontStyle fs;

    StringBuffer sb = new StringBuffer();
    Matcher m = SPANS_WITH_CLASS.matcher(snippet);
    while (m.find()) {
        fs = fsc.getFontStyleByCssClass(m.group(1));
        // logger.info("fs:" + fs);

        // Rigorous: if at list once no css class has been found return str
        // as it is
        if (fs == null) {
            return snippet;
        } else {
            m.appendReplacement(sb, "<style" + fs.getStyleAttributes() + ">$2</style>");
        }
    }
    snippet = m.appendTail(sb).toString();

    /*
     * //escape all non-escaped & snippet = Utils.replaceAllTotal(snippet, AMPS_ALONE, "&amp;");
     * 
     * snippet = escapeMarkupTags(snippet);
     */
    // logger.info("processed snippet:" + snippet);

    return snippet;
}

From source file:com.t3.model.MacroButtonProperties.java

private static String modifySortString(String str) {
    StringBuffer result = new StringBuffer();
    Matcher matcher = sortStringPattern.matcher(str);
    while (matcher.find()) {
        matcher.appendReplacement(result, paddingString(matcher.group(1), 4, '0', true));
    }// w  w w  .  j a v a  2  s  . c  o  m
    matcher.appendTail(result);
    return result.toString();
}

From source file:de.mpg.escidoc.services.citationmanager.utils.XsltHelper.java

/**
 * Converts snippet &lt;span&gt; tags to the appropriate JasperReport Styled
 * Text. Note: If at least one &lt;span&gt; css class will not match
 * FontStyle css, the snippet will be returned without any changes.
 * /* w  w  w .  ja  v a  2s . c  om*/
 * @param snippet
 * @return converted snippet
 * @throws CitationStyleManagerException
 */
public static String convertSnippetToJasperStyledText(String cs, String snippet)
        throws CitationStyleManagerException {

    //logger.info("input snippet:" + snippet);      

    snippet = removeI18N(snippet);

    FontStylesCollection fsc = XmlHelper.loadFontStylesCollection(cs);

    if (!Utils.checkVal(snippet) || fsc == null)
        return snippet;

    FontStyle fs;

    StringBuffer sb = new StringBuffer();
    Matcher m = SPANS_WITH_CLASS.matcher(snippet);
    while (m.find()) {
        fs = fsc.getFontStyleByCssClass(m.group(1));
        // logger.info("fs:" + fs);

        // Rigorous: if at list once no css class has been found return str
        // as it is
        if (fs == null) {
            return snippet;
        } else {
            m.appendReplacement(sb, "<style" + fs.getStyleAttributes() + ">$2</style>");
        }
    }
    snippet = m.appendTail(sb).toString();

    /*
    //escape all non-escaped & 
    snippet = Utils.replaceAllTotal(snippet, AMPS_ALONE, "&amp;");
            
    snippet = escapeMarkupTags(snippet);
    */
    //logger.info("processed snippet:" + snippet);

    return snippet;
}

From source file:gsn.storage.SQLUtils.java

/**
 * Table renaming, note that the renameMapping should be a tree map. This
 * method gets a sql query and changes the table names using the mappings
 * provided in the second argument.<br>
 * //from w  w  w.  j a  v a 2s. c o  m
 * @param query
 * @param renameMapping
 * @return
 */
public static StringBuilder newRewrite(CharSequence query, TreeMap<CharSequence, CharSequence> renameMapping) {
    // Selecting strings between pair of "" : (\"[^\"]*\")
    // Selecting tableID.tableName or tableID.* : (\\w+(\\.(\w+)|\\*))
    // The combined pattern is : (\"[^\"]*\")|(\\w+\\.((\\w+)|\\*))
    Pattern pattern = Pattern.compile("(\"[^\"]*\")|((\\w+)(\\.((\\w+)|\\*)))", Pattern.CASE_INSENSITIVE);
    Matcher matcher = pattern.matcher(query);
    StringBuffer result = new StringBuffer();
    if (!(renameMapping.comparator() instanceof CaseInsensitiveComparator))
        throw new RuntimeException("Query rename needs case insensitive treemap.");
    while (matcher.find()) {
        if (matcher.group(2) == null)
            continue;
        String tableName = matcher.group(3);
        CharSequence replacement = renameMapping.get(tableName);
        // $4 means that the 4th group of the match should be appended to the
        // string (the forth group contains the field name).
        if (replacement != null)
            matcher.appendReplacement(result, new StringBuilder(replacement).append("$4").toString());
    }
    String toReturn = matcher.appendTail(result).toString().toLowerCase();

    //TODO " from " has to use regular expressions because now from is separated through space which is not always the case, for instance if the user uses \t(tab) for separating "from" from the rest of the query, then we get exception. The same issue with other sql keywords in this method.

    int indexOfFrom = toReturn.indexOf(" from ") >= 0 ? toReturn.indexOf(" from ") + " from ".length() : 0;
    int indexOfWhere = (toReturn.lastIndexOf(" where ") > 0 ? (toReturn.lastIndexOf(" where "))
            : toReturn.length());
    String selection = toReturn.substring(indexOfFrom, indexOfWhere);
    Pattern fromClausePattern = Pattern.compile("\\s*(\\w+)\\s*", Pattern.CASE_INSENSITIVE);
    Matcher fromClauseMather = fromClausePattern.matcher(selection);
    result = new StringBuffer();
    while (fromClauseMather.find()) {
        if (fromClauseMather.group(1) == null)
            continue;
        String tableName = fromClauseMather.group(1);
        CharSequence replacement = renameMapping.get(tableName);
        if (replacement != null)
            fromClauseMather.appendReplacement(result, replacement.toString() + " ");
    }
    String cleanFromClause = fromClauseMather.appendTail(result).toString();
    String finalResult = StringUtils.replace(toReturn, selection, cleanFromClause);
    return new StringBuilder(finalResult);
}

From source file:org.jumpmind.util.FormatUtils.java

/**
 * Replace the keys found in the target text with the values found in the
 * replacements map.//from   w  w w  . j  a  v  a  2  s  .  c o  m
 * 
 * @param text
 *            The text to replace
 * @param replacements
 *            The map that contains the replacement values
 * @param matchUsingPrefixSuffix
 *            If true, look for the $(key) pattern to replace. If false,
 *            just replace the key outright.
 * @return The text with the token keys replaced
 */
public static String replaceTokens(String text, Map<?, ?> replacements, boolean matchUsingPrefixSuffix) {
    if (text != null && replacements != null && replacements.size() > 0) {
        if (matchUsingPrefixSuffix) {
            Matcher matcher = pattern.matcher(text);
            StringBuffer buffer = new StringBuffer();
            while (matcher.find()) {
                String[] match = matcher.group(1).split("\\|");
                String replacement = (String) replacements.get(match[0]);
                if (replacement != null) {
                    matcher.appendReplacement(buffer, "");
                    if (match.length == 2) {
                        replacement = formatString(match[1], replacement);
                    }
                    buffer.append(replacement);
                }
            }
            matcher.appendTail(buffer);
            text = buffer.toString();
        } else {
            for (Object key : replacements.keySet()) {
                text = text.replaceAll(key.toString(), (String) replacements.get(key));
            }
        }
    }
    return text;

}