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:au.edu.anu.portal.portlets.tweetal.servlet.TweetalServlet.java

private String replaceHashTag(String statusText) {
    Pattern p = Pattern.compile("(\\s|\\A)#([^\\s]+)");
    Matcher m = p.matcher(statusText);

    // if we have a match anywhere in the string
    StringBuffer buf = new StringBuffer();
    while (m.find()) {
        //replace that portion that matched, with the link
        String matched = m.group();
        m.appendReplacement(buf,
                String.format("<a target=\"_blank\" href=\"http://twitter.com/search?q=%%23%s\">%s</a>",
                        StringUtils.stripStart(matched.substring(1), "#"), matched));
    }//from  ww w  .  ja  va 2  s .  c o m
    m.appendTail(buf);
    return buf.toString();
}

From source file:it.wingstech.csslesser.LessifyMojo.java

private String inline(File f, String prefix) throws MojoExecutionException {
    if (f.isFile()) {
        getLog().info("Inlining file: " + f.getAbsolutePath() + " ...");
        try {/*from   ww w.j a v a  2 s  . c o  m*/
            String content = FileUtils.readFileToString(f);
            Pattern p = Pattern.compile("(" + Pattern.quote("@import url(") + "[\\'\\\"]?)(.*?)([\\'\\\"]?"
                    + Pattern.quote(");") + ")");

            Matcher m = p.matcher(content);
            StringBuffer sb = new StringBuffer();

            while (m.find() == true) {
                String url = m.group(2);
                getLog().info("   importing file: " + url + " ...");
                String cPrefix = ".";
                int ix = url.lastIndexOf("/");
                if (ix > 0) {
                    cPrefix = url.substring(0, ix);
                }

                String inputReplacement = inline(
                        new File(f.getParentFile().getAbsolutePath() + File.separator + m.group(2)), cPrefix);
                m.appendReplacement(sb, inputReplacement);
            }
            m.appendTail(sb);

            String result = sb.toString();

            FileUtils.writeStringToFile(f, result);

            StringBuffer sbIncludeImages = new StringBuffer();
            Pattern pImgReplacement = Pattern.compile(
                    "(" + Pattern.quote("url(") + "[\\'\\\"]?)(.*?)([\\'\\\"]?" + Pattern.quote(")") + ")");
            Matcher mImgReplacement = pImgReplacement.matcher(result);
            while (mImgReplacement.find() == true) {
                String urlImage = mImgReplacement.group(2);

                if (!urlImage.startsWith("/")) {
                    urlImage = prefix + "/" + urlImage;
                }
                mImgReplacement.appendReplacement(sbIncludeImages, "url('" + urlImage + "')");

            }
            mImgReplacement.appendTail(sbIncludeImages);

            return sbIncludeImages.toString();

        } catch (Exception ex) {
            throw new MojoExecutionException(ex.getMessage() + " on file " + f.getAbsolutePath(), ex);
        }
    }
    return "";
}

From source file:org.rakam.client.builder.document.SlateDocumentGenerator.java

public void generateTo(InputStream template, OutputStream dest) throws IOException {
    this.templates = generateExampleUsages();
    try (BufferedReader reader = new BufferedReader(new InputStreamReader(template));
            PrintWriter writer = new PrintWriter(new OutputStreamWriter(dest))) {
        String line;//from w  w w.j  a v a2s . com
        while ((line = reader.readLine()) != null) {
            Matcher matcher = PLACEHOLDER_PATTERN.matcher(line);
            StringBuffer buffer = new StringBuffer();
            while (matcher.find()) {
                String key = matcher.group(1);
                System.out.println("replacing:" + key);
                matcher.appendReplacement(buffer, generateContent(key));
            }
            matcher.appendTail(buffer);
            writer.println(buffer);
        }
    } catch (Exception e) {
        System.out.println("failed generating slate:" + e);
        e.printStackTrace();
    }
}

From source file:com.hichinaschool.flashcards.libanki.Media.java

/**
 * Percent-escape UTF-8 characters in local image filenames.
 * // w  ww . ja v a 2 s.  c o m
 * @param string The string to search for image references and escape the filenames.
 * @return The string with the filenames of any local images percent-escaped as UTF-8.
 */
public String escapeImages(String string) {
    Matcher m = fMediaRegexps[1].matcher(string);
    StringBuffer sb = new StringBuffer();
    while (m.find()) {
        if (fRemoteFilePattern.matcher(m.group(2)).find()) {
            m.appendReplacement(sb, m.group());
        } else {
            String tagBegin = m.group(1).substring(0, m.start(2));
            String fname = m.group(2);
            String tagEnd = m.group(1).substring(m.end(2));
            String tag = tagBegin + Uri.encode(fname) + tagEnd;
            m.appendReplacement(sb, tag);
        }
    }
    m.appendTail(sb);
    return sb.toString();
}

From source file:info.magnolia.cms.gui.dialog.DialogFckEdit.java

/**
 * @param value//w w w .ja  v a2  s. co  m
 * @return
 */
private String convertToView(String value) {
    String tmp = value;
    if (tmp != null) {
        tmp = tmp.replaceAll("\r\n", "<br />"); //$NON-NLS-1$ //$NON-NLS-2$
        tmp = tmp.replaceAll("\n", "<br />"); //$NON-NLS-1$ //$NON-NLS-2$

        value = LinkUtil.convertUUIDsToAbsoluteLinks(value);

        Pattern imagePattern = Pattern.compile("(<(a|img)[^>]+(src|href)[ ]*=[ ]*\")([^\"]*)(\"[^>]*>)"); //$NON-NLS-1$

        Matcher matcher = imagePattern.matcher(value);
        StringBuffer res = new StringBuffer();
        while (matcher.find()) {
            String src = matcher.group(4);

            // process only internal and relative links
            if (!Pattern.matches("^\\w*://.*", src) && !src.startsWith("/")) {
                String link = this.getRequest().getContextPath() + this.getTopParent().getConfigValue("path")
                        + "/" + StringUtils.substringAfter(src, "/");

                matcher.appendReplacement(res, "$1" + link + "$5"); //$NON-NLS-1$
            }
        }
        matcher.appendTail(res);
        return res.toString();
    }

    return StringUtils.EMPTY;
}

From source file:org.finra.dm.service.helper.Hive13DdlGenerator.java

/**
 * Escapes single quote characters, if not already escaped, with an extra backslash.
 *
 * @param string the input text/*from   w  w w  .  j  a  v  a  2 s  . c o  m*/
 *
 * @return the output text with all single quote characters escaped by an extra backslash
 */
public String escapeSingleQuotes(String string) {
    Pattern pattern = Pattern.compile("(?<!\\\\)(')");
    Matcher matcher = pattern.matcher(string);
    StringBuffer stringBuffer = new StringBuffer();

    while (matcher.find()) {
        matcher.appendReplacement(stringBuffer, matcher.group(1).replace("'", "\\\\'"));
    }
    matcher.appendTail(stringBuffer);

    return stringBuffer.toString();
}

From source file:by.heap.remark.convert.TextCleaner.java

/**
 * Handles running the regex-based replacements in the input
 * @param input String to process/*from w  ww  .  j av  a 2s  . c o m*/
 * @param regex Pattern to use
 * @return cleaned up input string
 */
private StringBuffer doReplacements(CharSequence input, Pattern regex) {
    StringBuffer output = new StringBuffer();

    Matcher m = regex.matcher(input);
    while (m.find()) {
        String repString;
        // if we have a hard match, do a simple replacement.
        String replacementKey = m.group().toLowerCase(Locale.ENGLISH);
        if (replacements.containsKey(replacementKey)) {
            repString = replacements.get(replacementKey);
        } else {
            // special case for escaped HTML entities.
            repString = "\\\\&$1";
        }
        m.appendReplacement(output, repString);
    }
    m.appendTail(output);

    return output;
}

From source file:com.agimatec.validation.jsr303.DefaultMessageInterpolator.java

private String replaceAnnotationAttributes(String message, Map<String, Object> annotationParameters) {
    Matcher matcher = messageParameterPattern.matcher(message);
    StringBuffer sb = new StringBuffer();
    while (matcher.find()) {
        String resolvedParameterValue;
        String parameter = matcher.group(1);
        Object variable = annotationParameters.get(removeCurlyBrace(parameter));
        if (variable != null) {
            if (variable.getClass().isArray()) {
                resolvedParameterValue = ArrayUtils.toString(variable);
            } else {
                resolvedParameterValue = variable.toString();
            }/*from w  w  w  . java2s.com*/
        } else {
            resolvedParameterValue = message;
        }
        matcher.appendReplacement(sb, resolvedParameterValue);
    }
    matcher.appendTail(sb);
    return sb.toString();
}

From source file:com.microsoft.tfs.client.common.ui.helpers.HTMLIncludeHelper.java

/**
 * <p>//from  w  ww .  ja v  a 2 s . co m
 * Transforms the given line, including referenced localized messages by
 * delegating to the {@link HTMLIncludeResourceProvider}.
 * </p>
 *
 * <p>
 * Lines with text matching: %%%MESSAGE(key)%%% will be transformed by
 * replacing the line with the results of the
 * {@link HTMLIncludeResourceProvider}'s response to the given key.
 *
 * <p>
 * Example:
 * </p>
 *
 * <p>
 * %%%MESSAGE(ClassName.MessageKey)%%% will include the given message for
 * the key ClassName.MessageKey.
 * </p>
 *
 * @param input
 *        An input line from a resource
 * @return The line with any message statements transformed.
 * @throws IOException
 *         If any included resources could not be read
 */
private String transformMessages(final String input) throws IOException {
    Check.notNull(input, "input"); //$NON-NLS-1$

    final Matcher messageMatcher = messagePattern.matcher(input);
    final StringBuffer transformation = new StringBuffer();

    while (messageMatcher.find()) {
        String replacement = ""; //$NON-NLS-1$

        if (messageMatcher.groupCount() == 1) {
            replacement = resourceProvider.getMessage(messageMatcher.group(1));
        } else {
            log.warn(MessageFormat.format("Could not transform message constant {0}: no messages class defined", //$NON-NLS-1$
                    messageMatcher.group(0)));
        }

        messageMatcher.appendReplacement(transformation, replacement);
    }

    messageMatcher.appendTail(transformation);

    return transformation.toString();
}

From source file:au.edu.anu.portal.portlets.tweetal.servlet.TweetalServlet.java

private String replaceUserReference(String statusText) {
    Pattern p = Pattern.compile("@[a-zA-Z0-9_]+");
    Matcher m = p.matcher(statusText);

    // if we have a match anywhere in the string
    StringBuffer buf = new StringBuffer();
    while (m.find()) {
        //replace that portion that matched, with the link
        String linkId = StringUtils.stripStart(m.group(), "@");
        m.appendReplacement(buf,
                String.format("<a target=\"_blank\" href=\"http://twitter.com/%s\">%s</a>", linkId, m.group()));
    }/*w w w . j a va2s. co m*/
    m.appendTail(buf);
    return buf.toString();
}