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:br.com.diegosilva.jsfcomponents.util.Utils.java

public static String escapeHtml(String string, boolean convertNewlines, boolean convertSpaces) {
    if (string == null)
        return null;
    StringBuilder sb = new StringBuilder();
    String htmlEntity;// w  w w.ja va 2s .c o m
    char c;
    for (int i = 0; i < string.length(); ++i) {
        htmlEntity = null;
        c = string.charAt(i);
        switch (c) {
        case '<':
            htmlEntity = "&lt;";
            break;
        case '>':
            htmlEntity = "&gt;";
            break;
        case '&':
            htmlEntity = "&amp;";
            break;
        case '"':
            htmlEntity = "&quot;";
            break;
        }
        if (htmlEntity != null) {
            sb.append(htmlEntity);
        } else {
            sb.append(c);
        }
    }
    String result = sb.toString();
    if (convertSpaces) {
        // Converts the _beginning_ of line whitespaces into non-breaking
        // spaces
        Matcher matcher = Pattern.compile("(\\n+)(\\s*)(.*)").matcher(result);
        StringBuffer temp = new StringBuffer();
        while (matcher.find()) {
            String group = matcher.group(2);
            StringBuilder spaces = new StringBuilder();
            for (int i = 0; i < group.length(); i++) {
                spaces.append("&#160;");
            }
            matcher.appendReplacement(temp, "$1" + spaces.toString() + "$3");
        }
        matcher.appendTail(temp);
        result = temp.toString();
    }
    if (convertNewlines) {
        result = result.replaceAll("\n", "<br/>");
    }
    return result;
}

From source file:org.ejbca.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. j a v  a  2 s . co m
    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: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./* w  ww  . ja v  a  2  s  . 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: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.
 * //from   www  .  j  a v  a2 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: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>
 * /*w w w  .ja v  a2  s .  c  om*/
 * @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:com.cubusmail.mail.text.MessageTextUtil.java

/**
 * Convert a plaint text to html.//from   w  w w.ja  v  a2 s  .co m
 * 
 * @param plainText
 * @return
 */
public static String convertPlainText2Html(String plainText, MessageTextMode mode) {

    try {
        plainText = HtmlUtils.htmlEscape(plainText).replaceAll(REPL_LINEBREAK, HTML_BR);

        final Matcher m = PATTERN_HREF.matcher(plainText);
        final StringBuffer sb = new StringBuffer(plainText.length());
        final StringBuilder tmp = new StringBuilder(256);
        while (m.find()) {
            final String nonHtmlLink = m.group(1);
            if ((nonHtmlLink == null) || (hasSrcAttribute(plainText, m.start(1)))) {
                m.appendReplacement(sb, Matcher.quoteReplacement(checkTarget(m.group())));
            } else {
                tmp.setLength(0);
                m.appendReplacement(sb, tmp.append("<a href=\"").append(
                        (nonHtmlLink.startsWith("www") || nonHtmlLink.startsWith("news") ? "http://" : ""))
                        .append("$1\" target=\"_blank\">$1</a>").toString());
            }
        }
        m.appendTail(sb);

        if (mode == MessageTextMode.DISPLAY) {
            sb.insert(0, "<p style=\"font-family: monospace; font-size: 10pt;\">");
            sb.append("</p>");
        }

        return sb.toString();
    } catch (final Exception e) {
        log.error(e.getMessage(), e);
    } catch (final StackOverflowError error) {
        log.error(StackOverflowError.class.getName(), error);
    }

    return plainText;
}

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));
    }//  www.j a  v a  2  s. co m
    matcher.appendTail(result);
    return result.toString();
}

From source file:com.hexidec.ekit.component.HTMLUtilities.java

public static String ensureInlineContent(String s) {
    if (StringUtils.isEmpty(s)) {
        return s;
    }/*w w w .  j ava  2s.  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:net.sf.jabref.util.Util.java

/**
 * Takes a string that contains bracketed expression and expands each of these using getFieldAndFormat.
 * <p>//  w  w w  . j  a  va 2s .c  om
 * 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:com.hexidec.ekit.component.HTMLUtilities.java

private static String converteBlocosEmParagrafos(String str) {

    Matcher m = pBlocos.matcher(str);
    if (!m.find()) {
        return str;
    }/*w w w. j  a va  2  s .com*/

    StringBuffer sb = new StringBuffer();
    String antes, depois;
    do {
        antes = m.group(1);
        depois = m.group(2);

        m.appendReplacement(sb, Matcher.quoteReplacement(antes + "p" + depois));

    } while (m.find());

    m.appendTail(sb);

    return sb.toString();
}