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:io.hummer.util.test.GenericTestResult.java

public String replace(String in, Map<String, String> searchReplace, int maxParallelReplacements) {

    if (searchReplace == null || searchReplace.isEmpty())
        return in;

    Map<String, String> thisSearchReplace = new HashMap<String, String>();
    int i = 0;/*from  ww w.j  a  v a2 s. c o m*/
    for (String s : searchReplace.keySet()) {
        if ((i++) >= maxParallelReplacements)
            break;
        thisSearchReplace.put(s, searchReplace.get(s));
    }

    String patternString = "(" + StringUtils.join(thisSearchReplace.keySet(), "|") + ")";

    for (String s : thisSearchReplace.keySet())
        searchReplace.remove(s);

    Pattern pattern = Pattern.compile(patternString);
    Matcher matcher = pattern.matcher(in);

    StringBuffer sb = new StringBuffer();
    while (matcher.find()) {
        matcher.appendReplacement(sb, thisSearchReplace.get(matcher.group(1)));
    }
    matcher.appendTail(sb);

    in = sb.toString();

    if (searchReplace.size() > 0)
        return replace(in, searchReplace, maxParallelReplacements);

    return in;
}

From source file:com.xpn.xwiki.content.parsers.DocumentParser.java

/**
 * Parse the links contained into the passed content represent the raw content from a document
 * (as typed by the user) and replace links that matches the passed linkToLookFor Link with the
 * specified newLink link. The comparison between found links and the link to look for is done
 * by the ReplaceLinkHandler passed as parameter.
 *
 * @param contentToParse the raw document content to parse.
 * @param linkToLookFor the link to look for that will be replaced by the new link
 * @param newLink the new link//from w ww  .  j av  a  2s .c o m
 * @param linkHandler the handler to use for comparing the links and for deciding what the
 *        replaced link will look like. For example two links may be pointing to the same
 *        document but one link may have a different alias or target. The handler decides
 *        what to do in these cases.
 * @param currentSpace the space to use for normalizing links. This is used for links that have
 *        no space defined.
 * @return a list of {@link Link} objects containing the parsed links, a list of invalid
 *         link contents found and a list of replaced links, returned as a
 *         {@link ReplacementResultCollection}. This allows users of this method to decide what
 *         they want to do with invalid links (like report them to the user, fix them, generate
 *         an error, etc).
 */
public ReplacementResultCollection parseLinksAndReplace(String contentToParse, Link linkToLookFor, Link newLink,
        ReplaceLinkHandler linkHandler, String currentSpace) {
    ReplacementResultCollection results = new ReplacementResultCollection();
    LinkParser linkParser = new LinkParser();
    Matcher matcher = LINK_PATTERN.matcher(contentToParse);
    StringBuffer modifiedContent = new StringBuffer();

    Link normalizedLinkToLookFor = linkToLookFor.getNormalizedLink(currentSpace);
    Link nomalizedNewLink = newLink.getNormalizedLink(currentSpace);

    while (matcher.find()) {
        Link foundLink = parseLink(linkParser, matcher.group(1), results);

        // Verify if the link found matches the link to look for
        if (foundLink != null) {
            Link normalizedFoundLink = foundLink.getNormalizedLink(currentSpace);

            if (linkHandler.compare(normalizedLinkToLookFor, normalizedFoundLink)) {

                // Compute the replacement string to use. This string must have "$" and
                // "\" symbols escaped as otherwise "$" will be considered as a regex group
                // replacement and "\" as a regex escape.
                // Note: We need to replace the "\" before the "$" as the "$" replacement
                // introduces other backslashes which would themselves be espaced...
                String replacementText = "["
                        + linkHandler.getReplacementLink(nomalizedNewLink, normalizedFoundLink).toString()
                        + "]";
                replacementText = StringUtils.replace(replacementText, "\\", "\\\\");
                replacementText = StringUtils.replace(replacementText, "$", "\\$");

                matcher.appendReplacement(modifiedContent, replacementText);
                results.addReplacedElement(normalizedFoundLink);
            }
        }
    }
    matcher.appendTail(modifiedContent);
    results.setModifiedContent(modifiedContent.toString());

    return results;
}

From source file:com.ibm.jaggr.core.impl.AbstractAggregatorImpl.java

@Override
public String substituteProps(String str, SubstitutionTransformer transformer) {
    if (str == null) {
        return null;
    }//from  w w w  .java 2 s . co m
    StringBuffer buf = new StringBuffer();
    Matcher matcher = pattern.matcher(str);
    while (matcher.find()) {
        String propName = matcher.group(1);
        String propValue = getPropValue(propName);
        if (propValue != null) {
            if (transformer != null) {
                propValue = transformer.transform(propName, propValue);
            }
            matcher.appendReplacement(buf, propValue.replace("\\", "\\\\") //$NON-NLS-1$ //$NON-NLS-2$
                    .replace("$", "\\$") //$NON-NLS-1$ //$NON-NLS-2$
            );
        } else {
            matcher.appendReplacement(buf, "\\${" + propName + "}"); //$NON-NLS-1$ //$NON-NLS-2$
        }
    }
    matcher.appendTail(buf);
    return buf.toString();
}

From source file:openthinks.others.htmlunit.PageKeeper.java

private StringBuffer keepStyleReference(String styleCtx) {
    Matcher matcher = RESOURCE_STYLE_REFERENCE_PATTERN.matcher(styleCtx);
    File refDir = new File(keepDir, RESOURCE_STYLE_REFERENCE_DIR);
    if (!refDir.exists())
        refDir.mkdirs();//from  w  ww. j  av a  2  s. co  m
    StringBuffer sb = new StringBuffer();
    while (matcher.find()) {
        String relativeURL = matcher.group(1);
        String styleRefUrl = getFullyQualifiedUrl(relativeURL);
        String styleRefName = getResourceName(styleRefUrl);
        String styleRefCtx = "";
        File keepFile = new File(refDir, styleRefName);
        WebResponse wrp = null;
        try {
            checkIfAlreadExist(keepFile);
            wrp = getResourceResponse(styleRefUrl);
            if (wrp.getContentType().startsWith("image") || wrp.getContentType().startsWith("IMAGE")) {
                ImageInputStream iis = ImageIO.createImageInputStream(wrp.getContentAsStream());
                Iterator<ImageReader> iter = ImageIO.getImageReaders(iis);
                ImageReader imageReader = iter.next();
                imageReader.setInput(iis);
                ImageIO.write(imageReader.read(0), imageReader.getFormatName(), keepFile);
            } else {
                styleRefCtx = wrp.getContentAsString("UTF-8");
                store(styleRefCtx, keepFile);
            }
            matcher.appendReplacement(sb, "url(" + RESOURCE_STYLE_REFERENCE_URL + "/" + styleRefName + ")");
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            matcher.appendReplacement(sb, "url(" + RESOURCE_STYLE_REFERENCE_URL + "/" + styleRefName + ")");
        } catch (NoSuchElementException e) {
            if (wrp != null) {
                styleRefCtx = wrp.getContentAsString("UTF-8");
                store(styleRefCtx, keepFile);
                matcher.appendReplacement(sb, "url(" + RESOURCE_STYLE_REFERENCE_URL + "/" + styleRefName + ")");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    matcher.appendTail(sb);
    return sb;
}

From source file:org.etudes.util.XrefHelper.java

/**
 * Replace any full URL references that include the server DNS, port, etc, with a root-relative one (i.e. starting with "/access" or "/library" or whatever)
 * /*from www. j av a2s.co m*/
 * @param data
 *        the html data.
 * @return The shortened data.
 */
public static String shortenFullUrls(String data) {
    if (data == null)
        return data;

    Pattern p = getPattern();
    Matcher m = p.matcher(data);
    StringBuffer sb = new StringBuffer();

    // for the relative access check: matches ..\..\access\ etc with any number of leading "../"
    Pattern relAccessPattern = Pattern.compile("^(../)+(access/.*)");

    // to fix our messed up URLs with this pattern:
    // /access/content/private/meleteDocs/3349d4ca-38f3-4744-00c6-26715545e441/module_339214362/../../../../access/meleteDocs/content/private/meleteDocs/3349d4ca-38f3-4744-00c6-26715545e441/uploads/applelogohistory.jpg
    Pattern messUpFixPattern = Pattern.compile("^/access/content/.*(../)+(access/.*)");

    // process each "harvested" string (avoiding like strings that are not in src= or href= patterns)
    while (m.find()) {
        if (m.groupCount() == 3) {
            String ref = m.group(2);
            String terminator = m.group(3);
            String origRef = ref;

            // if this is an access to our own server, shorten it to root relative (i.e. starting with "/access")
            int pos = internallyHostedUrl(ref);
            if (pos != -1) {
                ref = ref.substring(pos);
                m.appendReplacement(sb, Matcher.quoteReplacement(m.group(1) + "=\"" + ref + terminator));
            }

            // if this is a relative access URL, fix it
            else {
                Matcher relAccessMatcher = relAccessPattern.matcher(ref);
                if (relAccessMatcher.matches()) {
                    ref = "/" + relAccessMatcher.group(2);
                    m.appendReplacement(sb, Matcher.quoteReplacement(m.group(1) + "=\"" + ref + terminator));
                }

                // fix a botched attempt a xref fixing that got tripped up with ../../../../access relative references
                else {
                    Matcher messUpFixer = messUpFixPattern.matcher(ref);
                    if (messUpFixer.matches()) {
                        ref = "/" + messUpFixer.group(2);
                        m.appendReplacement(sb,
                                Matcher.quoteReplacement(m.group(1) + "=\"" + ref + terminator));
                        M_log.warn("shortenFullUrls: fixing ref: " + origRef + " : to : " + ref);
                    }
                }
            }
        }
    }

    m.appendTail(sb);

    return sb.toString();
}

From source file:org.botlibre.util.Utils.java

public static String linkHTML(String text) {
    if (text == null || text.isEmpty()) {
        return "";
    }/*from w w w .  j  av  a 2 s.com*/
    boolean http = text.indexOf("http") != -1;
    boolean www = text.indexOf("www.") != -1;
    boolean email = text.indexOf("@") != -1;
    if (!http && !www && !email) {
        return text;
    }
    if (text.indexOf("<") != -1 && text.indexOf(">") != -1) {
        return text;
    }
    if (http) {
        Matcher matcher = httpRegex.matcher(text);
        StringBuffer sb = new StringBuffer();
        while (matcher.find()) {
            String url = matcher.group();
            if (url.indexOf(".png") != -1 || url.indexOf(".jpg") != -1 || url.indexOf(".jpeg") != -1
                    || url.indexOf(".gif") != -1 || url.indexOf(".PNG") != -1 || url.indexOf(".JPG") != -1
                    || url.indexOf(".JPEG") != -1 || url.indexOf(".GIF") != -1) {
                url = "<a href='" + url + "' target='_blank'><img src='" + url + "' height='50'></a>";
            } else if (url.indexOf(".mp4") != -1 || url.indexOf(".webm") != -1 || url.indexOf(".ogg") != -1
                    || url.indexOf(".MP4") != -1 || url.indexOf(".WEBM") != -1 || url.indexOf(".OGG") != -1) {
                url = "<a href='" + url + "' target='_blank'><video src='" + url + "' height='50'></a>";
            } else if (url.indexOf(".wav") != -1 || url.indexOf(".mp3") != -1 || url.indexOf(".WAV") != -1
                    || url.indexOf(".MP3") != -1) {
                url = "<a href='" + url + "' target='_blank'><audio src='" + url + "' controls>audio</a>";
            } else {
                url = "<a href='" + url + "' target='_blank'>" + url + "</a>";
            }
            matcher.appendReplacement(sb, url);
        }
        matcher.appendTail(sb);
        text = sb.toString();
    } else if (www) {
        Matcher matcher = wwwRegex.matcher(text);
        StringBuffer sb = new StringBuffer();
        while (matcher.find()) {
            String url = matcher.group();
            matcher.appendReplacement(sb, "<a href='http://" + url + "' target='_blank'>" + url + "</a>");
        }
        matcher.appendTail(sb);
        text = sb.toString();
    }

    // http://, https://, ftp://
    //var urlPattern = /\b(?:https?|ftp):\/\/[a-z0-9-+&@#\/%?=~_|!:,.;]*[a-z0-9-+&@#\/%=~_|]/gim;

    // www. 
    // var wwwPattern = /(^|[^\/])(www\.[\S]+(\b|$))/gim;

    // name@domain.com
    if (email) {
        Matcher matcher = emailRegex.matcher(text);
        StringBuffer sb = new StringBuffer();
        while (matcher.find()) {
            String address = matcher.group();
            matcher.appendReplacement(sb,
                    "<a href='mailto://" + address + "' target='_blank'>" + address + "</a>");
        }
        matcher.appendTail(sb);
        text = sb.toString();
    }
    return text;
}

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

/**
 * <p>/*from w  w  w  . j ava2 s.co m*/
 * Transforms the given line, including referenced files by delegating to
 * the {@link HTMLIncludeResourceProvider}.
 * </p>
 *
 * <p>
 * Lines with text matching: %%%INCLUDE(file="filename")%%% will be
 * transformed by replacing the line with the given filename. The "format"
 * tag may also be specified with a value of "text" or "base64". If the
 * format is specified as "text", the file will be reinterpreted while being
 * included (ie, includes in included files will also be included.) If the
 * format is specified as "base64", the file will be included as base64
 * data.
 * </p>
 *
 * <p>
 * Examples:
 * </p>
 *
 * <p>
 * %%%INCLUDE(file="filename")%%% will include the resource specified by
 * "filename".
 * </p>
 *
 * <p>
 * %%%INCLUDE(file="filename", format="text")%%% will include the resource
 * specified by "filename". (This is identical to the above example.)
 * </p>
 *
 * <p>
 * %%%INCLUDE(file="filename", format="base64")%%% will include the base64
 * representation of the resource specified by "filename".
 * </p>
 *
 * @param input
 *        An input line from a resource
 * @return The line with any include statements transformed.
 * @throws IOException
 *         If any included resources could not be read
 */
private String transformIncludes(final String input) throws IOException {
    Check.notNull(input, "input"); //$NON-NLS-1$

    final Matcher includeMatcher = includePattern.matcher(input);
    final StringBuffer transformation = new StringBuffer();

    while (includeMatcher.find()) {
        if (includeMatcher.groupCount() != 1) {
            log.warn(MessageFormat.format("Invalid include statement: {0}", includeMatcher.toString())); //$NON-NLS-1$
            continue;
        }

        final Matcher optionMatcher = optionPattern.matcher(includeMatcher.group(1));
        String resourceName = null;
        String format = "text"; //$NON-NLS-1$

        while (optionMatcher.find()) {
            if (optionMatcher.groupCount() != 2) {
                log.warn(MessageFormat.format("Invalid include statement: {0}", includeMatcher.group(1))); //$NON-NLS-1$
                continue;
            }

            if ("file".equals(optionMatcher.group(1))) //$NON-NLS-1$
            {
                resourceName = optionMatcher.group(2);
            } else if ("format".equals(optionMatcher.group(1))) //$NON-NLS-1$
            {
                format = optionMatcher.group(2);
            }
        }

        if (resourceName == null) {
            log.warn(MessageFormat.format("Invalid include statement: {0}", includeMatcher.group(1))); //$NON-NLS-1$
        } else if ("base64".equals(format)) //$NON-NLS-1$
        {
            includeMatcher.appendReplacement(transformation, readResourceToBase64(resourceName));
        } else {
            includeMatcher.appendReplacement(transformation, readResource(resourceName));
        }
    }

    includeMatcher.appendTail(transformation);

    return transformation.toString();
}

From source file:org.catnut.ui.ComposeTweetActivity.java

private void shorten() {
    String text = mText.getText().toString();
    final Matcher matcher = TweetTextView.WEB_URL.matcher(text);
    String urls = "";
    while (matcher.find()) {
        urls += matcher.group() + ""; // ?
    }// ww w  .j av  a2  s .  c  o  m
    // http request
    if (!TextUtils.isEmpty(urls)) {
        final ProgressDialog dialog = ProgressDialog.show(this, null, getString(R.string.converting), true,
                false);
        CatnutAPI api = StuffAPI.shorten(urls.split(""));
        mApp.getRequestQueue()
                .add(new JsonObjectRequest(api.method, api.uri, null, new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        matcher.reset(); // ?
                        JSONArray _urls = response.optJSONArray("urls");
                        StringBuffer sb = new StringBuffer();
                        int i = 0;
                        try {
                            while (matcher.find()) {
                                matcher.appendReplacement(sb, _urls.optJSONObject(i).optString("url_short"));
                                i++;
                            }
                            matcher.appendTail(sb);
                            mText.setText(sb);
                            mText.setSelection(mText.length());
                        } catch (Exception ex) {
                            Log.e(TAG, "replace shorten url error!", ex);
                        }
                        dialog.dismiss();
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        dialog.dismiss();
                        WeiboAPIError weiboAPIError = WeiboAPIError.fromVolleyError(error);
                        Toast.makeText(ComposeTweetActivity.this, weiboAPIError.error, Toast.LENGTH_SHORT)
                                .show();
                    }
                }));
    } else {
        Toast.makeText(this, getString(R.string.no_links_hint), Toast.LENGTH_SHORT).show();
    }
}

From source file:com.nttec.everychan.ui.downloading.HtmlBuilder.java

private String fixComment(String comment) {
    comment = comment.replaceAll("(?i)<aibquote>", "<span class=\"unkfunc\">")
            .replaceAll("(?i)</aibquote>", "</span>").replaceAll("(?i)<aibspoiler>", "<span class=\"spoiler\">")
            .replaceAll("(?i)</aibspoiler>", "</span>");
    Matcher m = A_HREF_PATTERN.matcher(comment);
    if (!m.find())
        return comment;
    StringBuffer sb = new StringBuffer();
    do {/* w w  w .j av  a 2 s .  co  m*/
        String group = m.group();
        String found = m.group(1);
        int oldPos = m.start(1) - m.start();
        int oldLen = found.length();

        String url;
        if (found.startsWith("#")) {
            try {
                String thisThreadUrl = chan.buildUrl(pageModel);
                int i = thisThreadUrl.indexOf('#');
                if (i != -1)
                    thisThreadUrl = thisThreadUrl.substring(0, i);
                String postNumber = chan.parseUrl(thisThreadUrl + found).postNumber;
                url = "#" + postNumber != null ? postNumber : pageModel.threadNumber;
            } catch (Exception e) {
                url = found;
            }
        } else {
            url = chan.fixRelativeUrl(found);
            try {
                UrlPageModel linkModel = chan.parseUrl(url);
                if (ChanModels.hashUrlPageModel(linkModel).equals(ChanModels.hashUrlPageModel(pageModel))) {
                    url = "#" + linkModel.postNumber;
                }
            } catch (Exception e) {
                /* ignore */ }
        }

        m.appendReplacement(sb, url.equals(found) ? group
                : (group.substring(0, oldPos) + url + group.substring(oldPos + oldLen)));
    } while (m.find());
    m.appendTail(sb);
    return sb.toString();
}