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:io.github.swagger2markup.markup.builder.internal.AbstractMarkupDocBuilder.java

protected void importMarkupStyle1(Pattern titlePattern, Markup titlePrefix, Reader markupText,
        MarkupLanguage markupLanguage, int levelOffset) {
    Validate.isTrue(levelOffset <= MAX_TITLE_LEVEL,
            String.format("Specified levelOffset (%d) > max levelOffset (%d)", levelOffset, MAX_TITLE_LEVEL));
    Validate.isTrue(levelOffset >= -MAX_TITLE_LEVEL,
            String.format("Specified levelOffset (%d) < min levelOffset (%d)", levelOffset, -MAX_TITLE_LEVEL));

    StringBuffer leveledText = new StringBuffer();
    try (BufferedReader bufferedReader = new BufferedReader(markupText)) {
        String readLine;//from w w  w.  j  ava 2s. c o  m
        while ((readLine = bufferedReader.readLine()) != null) {
            Matcher titleMatcher = titlePattern.matcher(readLine);

            while (titleMatcher.find()) {
                int titleLevel = titleMatcher.group(1).length() - 1;
                String title = titleMatcher.group(2);

                if (titleLevel + levelOffset > MAX_TITLE_LEVEL)
                    throw new IllegalArgumentException(String.format(
                            "Specified levelOffset (%d) set title '%s' level (%d) > max title level (%d)",
                            levelOffset, title, titleLevel, MAX_TITLE_LEVEL));
                if (titleLevel + levelOffset < 0)
                    throw new IllegalArgumentException(
                            String.format("Specified levelOffset (%d) set title '%s' level (%d) < 0",
                                    levelOffset, title, titleLevel));
                else
                    titleMatcher.appendReplacement(leveledText, Matcher.quoteReplacement(String.format("%s %s",
                            StringUtils.repeat(titlePrefix.toString(), 1 + titleLevel + levelOffset), title)));
            }
            titleMatcher.appendTail(leveledText);
            leveledText.append(newLine);
        }
    } catch (IOException e) {
        throw new RuntimeException("Failed to import Markup", e);
    }

    if (!StringUtils.isBlank(leveledText)) {
        documentBuilder.append(newLine);
        documentBuilder.append(convert(leveledText.toString(), markupLanguage));
        documentBuilder.append(newLine);
    }
}

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;//w w w.  ja  va 2  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:io.github.swagger2markup.markup.builder.internal.AbstractMarkupDocBuilder.java

protected void importMarkupStyle2(Pattern titlePattern, String titleFormat, boolean startFrom0,
        Reader markupText, MarkupLanguage markupLanguage, int levelOffset) {
    Validate.isTrue(levelOffset <= MAX_TITLE_LEVEL,
            String.format("Specified levelOffset (%d) > max levelOffset (%d)", levelOffset, MAX_TITLE_LEVEL));
    Validate.isTrue(levelOffset >= -MAX_TITLE_LEVEL,
            String.format("Specified levelOffset (%d) < min levelOffset (%d)", levelOffset, -MAX_TITLE_LEVEL));

    StringBuffer leveledText = new StringBuffer();
    try (BufferedReader bufferedReader = new BufferedReader(markupText)) {
        String readLine;//from  w  w  w .  j a  va2  s .  c  o  m
        while ((readLine = bufferedReader.readLine()) != null) {
            Matcher titleMatcher = titlePattern.matcher(readLine);

            while (titleMatcher.find()) {
                int titleLevel = Integer.valueOf(titleMatcher.group(1)) - (startFrom0 ? 0 : 1);
                String title = titleMatcher.group(2);

                if (titleLevel + levelOffset > MAX_TITLE_LEVEL)
                    throw new IllegalArgumentException(String.format(
                            "Specified levelOffset (%d) set title '%s' level (%d) > max title level (%d)",
                            levelOffset, title, titleLevel, MAX_TITLE_LEVEL));
                if (titleLevel + levelOffset < 0)
                    throw new IllegalArgumentException(
                            String.format("Specified levelOffset (%d) set title '%s' level (%d) < 0",
                                    levelOffset, title, titleLevel));
                else
                    titleMatcher.appendReplacement(leveledText, Matcher.quoteReplacement(String
                            .format(titleFormat, (startFrom0 ? 0 : 1) + titleLevel + levelOffset, title)));
            }
            titleMatcher.appendTail(leveledText);
            leveledText.append(newLine);
        }
    } catch (IOException e) {
        throw new RuntimeException("Failed to import Markup", e);
    }

    if (!StringUtils.isBlank(leveledText)) {
        documentBuilder.append(newLine);
        documentBuilder.append(convert(leveledText.toString(), markupLanguage));
        documentBuilder.append(newLine);
    }
}

From source file:com.ibm.jaggr.service.impl.transport.AbstractHttpTransport.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.  
 *//* w w w  . j  a v  a2s .c o m*/
protected JSONObject decodeModules(String encstr) throws IOException {
    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);
    JSONObject decoded = null;
    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$
    try {
        decoded = new JSONObject(jsonstr);
    } catch (JSONException e) {
        throw new BadRequestException(e);
    }
    return decoded;
}

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// w  w w .  java2s.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:org.botlibre.util.Utils.java

public static String linkHTML(String text) {
    if (text == null || text.isEmpty()) {
        return "";
    }// w w w.j  a  v a 2 s .  c om
    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:gtu._work.ui.RenameUI.java

private void usePatternNewNameBtnActionPerformed() {
    try {// www .ja v  a 2s.  c  om
        String findFileRegex = Validate.notBlank(findFileRegexText.getText(), "??Regex");
        String renameRegex = Validate.notBlank(renameRegexText.getText(), "??");
        Pattern renameRegexPattern = Pattern.compile("\\#(\\w+)\\#");
        Matcher matcher2 = null;

        Pattern findFileRegexPattern = Pattern.compile(findFileRegex, Pattern.CASE_INSENSITIVE);
        Matcher matcher = null;
        DefaultTableModel model = JTableUtil.createModel(false, "??", "??", "");

        int ind = 1;
        for (XFile f : fileList) {
            matcher = findFileRegexPattern.matcher(f.fileName);
            if (matcher.matches()) {
                StringBuffer sb = new StringBuffer();
                matcher2 = renameRegexPattern.matcher(renameRegex);
                while (matcher2.find()) {
                    String val = matcher2.group(1);
                    if (val.matches("\\d+L")) {
                        int index = Integer.parseInt(val.substring(0, val.length() - 1));
                        matcher2.appendReplacement(sb, DateFormatUtils
                                .format(Long.parseLong(matcher.group(index)), "yyyyMMdd_HHmmss"));
                    } else if (val.equalsIgnoreCase("date")) {
                        matcher2.appendReplacement(sb,
                                DateFormatUtils.format(f.file.lastModified(), "yyyyMMdd_HHmmss"));
                    } else if (val.equalsIgnoreCase("serial")) {
                        matcher2.appendReplacement(sb, String.valueOf(ind++));
                    } else if (StringUtils.isNumeric(val)) {
                        int index = Integer.parseInt(val);
                        matcher2.appendReplacement(sb, matcher.group(index));
                    }
                }
                matcher2.appendTail(sb);
                model.addRow(this.getXFile(f, sb.toString()));
            }
        }
        renameTable.setModel(model);
    } catch (Exception ex) {
        JCommonUtil.handleException(ex);
    }
}

From source file:org.archive.wayback.replay.html.transformer.JSStringTransformer.java

public String transform(ReplayParseContext context, String input) {
    StringBuffer replaced = new StringBuffer(input.length());
    Matcher m = pattern.matcher(input);
    while (m.find()) {
        String rawUrl = m.group(1);
        String pre = input.substring(m.start(), m.start(1));
        String post = input.substring(m.end(1), m.end());

        String origUrl = sourceEscaping != null ? sourceEscaping.unescape(rawUrl) : rawUrl;
        String url = context.contextualizeUrl(origUrl);

        if (url != origUrl) {
            // reverse some changes made to url by contextualizeUrl method, that
            // may break assumptions in subsequent JavaScript processing.
            // eg. "http://example.org" -> "/20140101012345/http://example.org/"
            // eg. "https://domain" + ".example.org" -> "http://domain/" + ".example.org"
            // eg. "https://domain." + "example.org" -> "http://domain" + "example.org"

            // remove trailing "/" if origUrl doesn't have it.  As Wayback does not need
            // trailing slash, it may make sense to this everywhere.  Just doing this fix
            // in JavaScript for now.
            if (url.endsWith("/") && !origUrl.endsWith("/")) {
                url = url.substring(0, url.length() - 1);
            }//from  ww  w. j  a va  2s .c o  m

            // add trailing "." (removed by canonicalizer) back, if origUrl has it.
            if (origUrl.endsWith(".") && !url.endsWith(".")) {
                url = url + ".";
            }

            if (sourceEscaping != null) {
                url = sourceEscaping.escape(url);
            }
        } else {
            // use the original rawUrl
            url = rawUrl;
        }
        m.appendReplacement(replaced, Matcher.quoteReplacement(pre + url + post));
    }
    m.appendTail(replaced);
    return replaced.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() + ""; // ?
    }//w  w  w  .jav a  2s.  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();
    }
}