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:hudson.plugins.emailext.plugins.content.BuildLogRegexContent.java

String getContent(BufferedReader reader) throws IOException {

    final boolean asHtml = matchedLineHtmlStyle != null;
    escapeHtml = asHtml || escapeHtml;/*w w w .  j a  v  a2s  . c om*/

    final Pattern pattern = Pattern.compile(regex);
    final StringBuffer buffer = new StringBuffer();
    int numLinesTruncated = 0;
    int numMatches = 0;
    int numLinesStillNeeded = 0;
    boolean insidePre = false;
    Queue<String> linesBeforeList = new LinkedList<String>();
    String line = null;
    while ((line = reader.readLine()) != null) {
        // Remove console notes (JENKINS-7402)
        line = ConsoleNote.removeNotes(line);

        // Remove any lines before that are no longer needed.
        while (linesBeforeList.size() > linesBefore) {
            linesBeforeList.remove();
            ++numLinesTruncated;
        }
        final Matcher matcher = pattern.matcher(line);
        final StringBuffer sb = new StringBuffer();
        boolean matched = false;
        while (matcher.find()) {
            matched = true;
            if (substText != null) {
                matcher.appendReplacement(sb, substText);
            } else {
                break;
            }
        }
        if (matched) {
            // The current line matches.
            if (showTruncatedLines == true && numLinesTruncated > 0) {
                // Append information about truncated lines.
                insidePre = stopPre(buffer, insidePre);
                appendLinesTruncated(buffer, numLinesTruncated, asHtml);
                numLinesTruncated = 0;
            }
            if (asHtml) {
                insidePre = startPre(buffer, insidePre);
            }
            while (!linesBeforeList.isEmpty()) {
                appendContextLine(buffer, linesBeforeList.remove(), escapeHtml);
            }
            // Append the (possibly transformed) current line.
            if (substText != null) {
                matcher.appendTail(sb);
                line = sb.toString();
            }
            appendMatchedLine(buffer, line, escapeHtml, matchedLineHtmlStyle, addNewline);
            ++numMatches;
            // Set up to add numLinesStillNeeded
            numLinesStillNeeded = linesAfter;
        } else {
            // The current line did not match.
            if (numLinesStillNeeded > 0) {
                // Append this line as a line after.
                appendContextLine(buffer, line, escapeHtml);
                --numLinesStillNeeded;
            } else {
                // Store this line as a possible line before.
                linesBeforeList.offer(line);
            }
        }
        if (maxMatches != 0 && numMatches >= maxMatches && numLinesStillNeeded == 0) {
            break;
        }
    }
    if (showTruncatedLines == true) {
        // Count the rest of the lines.
        // Include any lines in linesBefore.
        while (linesBeforeList.size() > 0) {
            linesBeforeList.remove();
            ++numLinesTruncated;
        }
        if (line != null) {
            // Include the rest of the lines that haven't been read in.
            while ((line = reader.readLine()) != null) {
                ++numLinesTruncated;
            }
        }
        if (numLinesTruncated > 0) {
            insidePre = stopPre(buffer, insidePre);
            appendLinesTruncated(buffer, numLinesTruncated, asHtml);
        }
    }
    insidePre = stopPre(buffer, insidePre);
    if (buffer.length() == 0) {
        return defaultValue;
    }
    return buffer.toString();
}

From source file:gtu._work.etc.EnglishTester.java

String formatChangeLine(String question, String answer) {
    answer = answer.replaceAll("\\[.*\\]", "");
    answer = answer.replaceAll("-", "");

    Pattern ptn = Pattern.compile(question, Pattern.CASE_INSENSITIVE);
    Matcher matcher = ptn.matcher(answer);
    StringBuffer sb = new StringBuffer();
    while (matcher.find()) {
        matcher.appendReplacement(sb, "");
    }/*w ww . ja  v a2 s .  c o  m*/
    matcher.appendTail(sb);
    return "<html>" + sb.toString() + "</html>";
}

From source file:mergedoc.core.Comment.java

/**
 * ???????//from  w  w w .  j ava 2s  .  c o m
 * <p>
 * @param o 
 */
private void shrinkComment(OutputComment o) {

    // ? Java ????
    String emptyDescRegex = "(?s)\\s*/\\*\\*\\s*\\*\\s*@.*";
    if (FastStringUtils.matches(srcBody, emptyDescRegex)) {
        docBody = null;
        o.build();
        if (o.resultHeight() <= o.originHeight) {
            return;
        }
    }

    // ? Java ????
    // -> buildComment ?????????????????
    boolean b1 = shrinkTagList("@see", sees);
    boolean b2 = shrinkTagList("@throws", throwses);
    boolean b3 = shrinkTagList("@param", params);
    boolean b4 = shrinkTagList("@return", returns);
    if (b1 || b2 || b3 || b4) {
        o.build();
        if (o.resultHeight() <= o.originHeight) {
            return;
        }
    }

    // ?
    int height = o.resultHeight();

    // ? <p> ????
    Pattern pTagPat = PatternCache.getPattern("<p>\n\n(<p>)");
    if (o.comment.contains("<p>\n\n<p>")) {
        StringBuffer sb = new StringBuffer();
        Matcher pTagMat = pTagPat.matcher(o.comment);
        while (height > o.originHeight && pTagMat.find()) {
            pTagMat.appendReplacement(sb, "$1");
            height -= 2;
        }
        pTagMat.appendTail(sb);
        o.comment = sb.toString();
        if (height <= o.originHeight) {
            return;
        }
    }

    // <th?<td?</tr ???
    Pattern tdTagPat = PatternCache.getPattern("\\s+(<(t[hd]|/tr))");
    if (o.comment.contains("<table")) {
        StringBuffer sb = new StringBuffer();
        Matcher tdTagMat = tdTagPat.matcher(o.comment);
        while (height > o.originHeight && tdTagMat.find()) {
            tdTagMat.appendReplacement(sb, "$1");
            height--;
        }
        tdTagMat.appendTail(sb);
        o.comment = sb.toString();
        if (height <= o.originHeight) {
            return;
        }
    }

    // <li?</ul?</ol ???
    Pattern liTagPat = PatternCache.getPattern("\\s+(<(li|/[uo]l))");
    if (o.comment.contains("<li")) {
        StringBuffer sb = new StringBuffer();
        Matcher liTagMat = liTagPat.matcher(o.comment);
        while (height > o.originHeight && liTagMat.find()) {
            liTagMat.appendReplacement(sb, "$1");
            height--;
        }
        liTagMat.appendTail(sb);
        o.comment = sb.toString();
        if (height <= o.originHeight) {
            return;
        }
    }

    // 
    Pattern emptyLinePat = PatternCache.getPattern("(?m)^\\s*?\n");
    Matcher emptyLineMat = emptyLinePat.matcher(o.comment);
    StringBuffer sb = new StringBuffer();
    while (height > o.originHeight && emptyLineMat.find()) {
        emptyLineMat.appendReplacement(sb, "");
        height--;
    }
    emptyLineMat.appendTail(sb);
    o.comment = sb.toString();
    if (height <= o.originHeight) {
        return;
    }

    //  Java ? 1 ????
    String firstLineRegex = "(?s)\\s*/\\*\\*\\s*\n.*";
    if (!FastStringUtils.matches(srcBody, firstLineRegex)) {
        o.enabledFirstLine = true;
        if (o.resultHeight() <= o.originHeight) {
            return;
        }
    }

    // ???
    final int maxWidth = 160;
    while (o.resultHeight() > o.originHeight && o.width < maxWidth) {

        o.build();
        if (o.resultHeight() <= o.originHeight) {
            return;
        }

        if (o.comment.contains("<")) {

            o.comment = pTagPat.matcher(o.comment).replaceAll("$1");
            if (o.resultHeight() <= o.originHeight) {
                return;
            }

            o.comment = tdTagPat.matcher(o.comment).replaceAll("$1");
            if (o.resultHeight() <= o.originHeight) {
                return;
            }

            o.comment = liTagPat.matcher(o.comment).replaceAll("$1");
            if (o.resultHeight() <= o.originHeight) {
                return;
            }
        }

        o.comment = emptyLinePat.matcher(o.comment).replaceAll("");
        if (o.resultHeight() <= o.originHeight) {
            return;
        }

        if (o.width < 100) {
            o.width += 4;
        } else {
            o.width += 8;
        }
    }
}

From source file:org.alfresco.web.bean.NavigationBean.java

/**
 * @param helpUrl The helpUrl to set.//from  w  w  w .  j  a  v  a 2 s .  c  om
 */
public void setHelpUrl(String helpUrl) {
    if (this.helpUrl == null) {
        Descriptor serverDescriptor = Repository.getServiceRegistry(FacesContext.getCurrentInstance())
                .getDescriptorService().getServerDescriptor();
        // search / replace each available key occurrence in the template string
        // Note: server descriptor is looking for "version.major", "version.minor", etc.
        Pattern p = Pattern.compile("\\{(\\w+\\.?\\w+)\\}");
        Matcher m = p.matcher(helpUrl);
        boolean result = m.find();
        if (result) {
            StringBuffer sb = new StringBuffer();
            String value = null;
            do {
                value = serverDescriptor.getDescriptor(m.group(1));
                m.appendReplacement(sb, value != null ? value : m.group(1));
                result = m.find();
            } while (result);
            m.appendTail(sb);
            helpUrl = sb.toString();
        }

        this.helpUrl = helpUrl;
    }
}

From source file:org.kuali.kfs.coa.batch.dataaccess.impl.AccountingPeriodFiscalYearMakerImpl.java

/**
 * this routine is provided to update string fields which contain two-digit years that need to be updated for display. it is
 * very specific, but it's necessary. "two-digit year" means the two numeric characters preceded by a non-numeric character.
 * /*from w  w  w  .j  ava 2  s.  com*/
 * @param newYear
 * @param oldYear
 * @param currentString
 * @return the updated string for a two digit year
 */
protected String updateTwoDigitYear(String newYear, String oldYear, String currentString) {
    // group 1 is the bounded by the outermost set of parentheses
    // group 2 is the first inner set
    // group 3 is the second inner set--a two-digit year at the beginning of the line
    String regExpString = "(([^0-9]{1}" + oldYear + ")|^(" + oldYear + "))";
    Pattern pattern = Pattern.compile(regExpString);
    Matcher matcher = pattern.matcher(currentString);

    // start looking for a match
    boolean matched = matcher.find();
    if (!matched) {
        // just return if nothing is found
        return currentString;
    }

    // we found something
    // we have to process it
    String returnString = currentString;
    StringBuffer outString = new StringBuffer();
    // is there a match at the beginning of the line (a match with group 3)?
    if (matcher.group(3) != null) {
        // there is a two-digit-year string at the beginning of the line
        // we want to replace it
        matcher.appendReplacement(outString, newYear);
        // find the next match if there is one
        matched = matcher.find();
    }

    while (matched) {
        // the new string will no longer match with group 3
        // if there is still a match, it will be with group 2
        // now we have to prefix the new year string with the same
        // non-numeric character as the next match (hyphen, space, whatever)
        String newYearString = matcher.group(2).substring(0, 1) + newYear;
        matcher.appendReplacement(outString, newYearString);
        matched = matcher.find();
    }

    // dump whatever detritus is left into the new string
    matcher.appendTail(outString);

    return outString.toString();
}

From source file:com.ibm.jaggr.core.impl.modulebuilder.css.CSSModuleBuilder.java

/**
 * Returns a regular expression for a filepath that can include standard
 * file system wildcard characters (e.g. * and ?)
 *
 * @param filespec A filespec that can contain wildcards
 * @return A regular expression to match paths specified by <code>filespec</code>
 *///from w  w w . j av  a2 s.co m
protected Pattern toRegexp(String filespec) {
    Matcher m = escaper.matcher(filespec);
    StringBuffer sb = new StringBuffer();
    while (m.find()) {
        String matched = m.group(0);
        if (matched.equals("*")) { //$NON-NLS-1$
            m.appendReplacement(sb, "\\[^/]*?"); //$NON-NLS-1$
        } else if (matched.equals("?")) { //$NON-NLS-1$
            m.appendReplacement(sb, "[^/]"); //$NON-NLS-1$
        } else if (matched.equals("$")) { //$NON-NLS-1$
            m.appendReplacement(sb, "\\\\\\$"); //$NON-NLS-1$
        } else if (matched.equals("\\")) { //$NON-NLS-1$
            m.appendReplacement(sb, "\\\\\\\\"); //$NON-NLS-1$
        } else {
            m.appendReplacement(sb, "\\\\" + matched); //$NON-NLS-1$
        }
    }
    m.appendTail(sb);
    String patStr = sb.toString();
    return Pattern.compile((patStr.startsWith("/") ? "" : "(^|/)") + //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
            patStr + "$", Pattern.CASE_INSENSITIVE); //$NON-NLS-1$
}

From source file:fr.fastconnect.factory.tibco.bw.maven.AbstractBWMojo.java

public String replaceProperties(String string) {
    if (string == null)
        return null;

    Matcher m = mavenPropertyPattern.matcher(string);

    StringBuffer sb = new StringBuffer();

    while (m.find()) {
        String propertyName = m.group(1);
        String propertyValue = getPropertyValue(propertyName);
        if (propertyValue != null) {
            m.appendReplacement(sb, Matcher.quoteReplacement(propertyValue));
        }/*from   ww w.  ja v a  2 s .  co  m*/
    }
    m.appendTail(sb);
    string = sb.toString();

    return string;
}

From source file:com.networknt.light.rule.form.AbstractFormRule.java

protected String enrichForm(String json, Map<String, Object> inputMap) throws Exception {
    Map<String, Object> data = (Map<String, Object>) inputMap.get("data");
    Pattern pattern = Pattern.compile("\\[\\{\"label\":\"dynamic\",([^]]+)\\}\\]");
    Matcher m = pattern.matcher(json);
    StringBuffer sb = new StringBuffer(json.length());
    while (m.find()) {
        String text = m.group(1);
        // get the values from rules.
        logger.debug("text = {}", text);
        text = text.substring(8);/*from   w  w w.j a v a  2 s  .c  o m*/
        logger.debug("text = {}", text);
        Map<String, Object> jsonMap = mapper.readValue(text, new TypeReference<HashMap<String, Object>>() {
        });
        jsonMap.put("payload", inputMap.get("payload"));
        // inject host into data here.
        Map<String, Object> dataMap = new HashMap<String, Object>();
        dataMap.put("host", data.get("host"));
        jsonMap.put("data", dataMap);
        RuleEngine.getInstance().executeRule(Util.getCommandRuleId(jsonMap), jsonMap);
        String result = (String) jsonMap.get("result");
        logger.debug("result = {}", result);
        if (result != null && result.length() > 0) {
            m.appendReplacement(sb, Matcher.quoteReplacement(result));
        } else {
            m.appendReplacement(sb, Matcher.quoteReplacement("[ ]"));
        }
    }
    m.appendTail(sb);
    logger.debug("form = {}", sb.toString());
    return sb.toString();
}

From source file:com.ibm.jaggr.core.impl.transport.RequestedModuleNames.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.
 *
 * @param encstr// w  ww  .j  a v  a 2 s. c o  m
 *            the encoded module name list
 * @return the decoded string as a JSON object
 *
 * @throws IOException
 * @throws JSONException
 */
protected JSONObject decodeModules(String encstr) throws IOException, JSONException {
    final String sourceMethod = "decodeModules"; //$NON-NLS-1$
    JSONObject result = null;
    if (isTraceLogging) {
        log.entering(RequestedModuleNames.class.getName(), sourceMethod, new Object[] { encstr });
    }
    if (encstr.length() == 0) {
        result = new JSONObject("{}"); //$NON-NLS-1$
    } else {
        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);
        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$
        result = new JSONObject(jsonstr);
    }
    if (isTraceLogging) {
        log.exiting(RequestedModuleNames.class.getName(), sourceMethod, result);
    }
    return result;
}

From source file:mergedoc.core.APIDocument.java

/**
 * HTML ? A  Javadoc ? link ????//  w w w  . ja  v  a2 s  .com
 * <p>
 * ?? Javadoc ?? Comment ?????????
 * ?????Javadoc ? see ?????????
 * ??????
 *
 * @param className ??
 * @param html HTML ? A ?
 * @return Javadoc link 
 */
private String formatLinkTag(String className, String html) {

    StringBuffer sb = new StringBuffer();
    Matcher linkMatcher = linkClassPattern.matcher(html);

    while (linkMatcher.find()) {

        String url = linkMatcher.group(1).trim();
        String label = linkMatcher.group(2).trim();
        String ref = formatClassName(className, url);
        Pattern methodRefPat = PatternCache.getPattern("-(.*)-$");
        Matcher methodRefMat = methodRefPat.matcher(ref);
        if (methodRefMat.find()) {
            ref = FastStringUtils.replaceAll(ref, "-(.*)-$", "($1)"); // for Java8
            ref = FastStringUtils.replace(ref, "-", ","); // for Java8
            ref = FastStringUtils.replace(ref, ":A", "[]"); // for Java8
        }

        StringBuilder link = new StringBuilder();
        link.append("{@link ");
        link.append(ref);
        if (label.length() > 0) {

            ref = ref.replace('#', '.');
            if (!ref.endsWith(label)) {
                link.append(" ");
                link.append(label);
            }
        }
        link.append("}");

        linkMatcher.appendReplacement(sb, link.toString());
    }
    linkMatcher.appendTail(sb);
    html = sb.toString();

    return html;
}