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:com.bellman.bible.android.control.link.LinkControl.java

/**
 * IBT use _nn_ for punctuation chars in references to dictionaries e.g. _32_ represents a space so 'Holy_32_Spirit' should be converted to 'Holy Spirit'
 *
 * @param ref Key e.g. dictionary key// www  .j  a v a 2 s. com
 * @return ref with _nn_ replaced by punctuation
 */
private String replaceIBTSpecialCharacters(String ref) {
    Matcher refIBTSpecialCharMatcher = IBT_SPECIAL_CHAR_RE.matcher(ref);
    StringBuffer output = new StringBuffer();
    while (refIBTSpecialCharMatcher.find()) {
        String specialChar = Character.toString((char) Integer.parseInt(refIBTSpecialCharMatcher.group(1)));
        refIBTSpecialCharMatcher.appendReplacement(output, specialChar);
    }
    refIBTSpecialCharMatcher.appendTail(output);
    return output.toString();
}

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

private String replaceVariables(String message, ResourceBundle bundle, Locale locale, boolean recurse) {
    Matcher matcher = messageParameterPattern.matcher(message);
    StringBuffer sb = new StringBuffer();
    String resolvedParameterValue;
    while (matcher.find()) {
        String parameter = matcher.group(1);
        resolvedParameterValue = resolveParameter(parameter, bundle, locale, recurse);

        matcher.appendReplacement(sb, resolvedParameterValue);
    }/*from  w w w .jav a  2s . co m*/
    matcher.appendTail(sb);
    return sb.toString();
}

From source file:edu.umd.cs.findbugs.util.Strings.java

/**
 * Unescape XML entities and illegal characters in the given string. This
 * enhances the functionality of// www.j  ava  2s .c om
 * org.apache.commons.lang.StringEscapeUtils.unescapeXml by unescaping
 * low-valued unprintable characters, which are not permitted by the W3C XML
 * 1.0 specification.
 *
 * @param s
 *            a string
 * @return the same string with XML entities/escape sequences unescaped
 * @see <a href="http://www.w3.org/TR/REC-xml/#charsets">Extensible Markup
 *      Language (XML) 1.0 (Fifth Edition)</a>
 * @see <a
 *      href="http://commons.apache.org/lang/api/org/apache/commons/lang/StringEscapeUtils.html#unescapeXml(java.lang.String)">org.apache.commons.lang.StringEscapeUtils
 *      javadoc</a>
 */
public static String unescapeXml(String s) {

    initializeEscapeMap();

    /*
     * we can't escape the string if the pattern doesn't compile! (but that
     * should never happen since the pattern is static)
     */
    if (!initializeUnescapePattern()) {
        return s;
    }

    if (s == null || s.length() == 0) {
        return s;
    }

    /*
     * skip this expensive check entirely if there are no substrings
     * resembling Unicode escape sequences in the string to be unescaped
     */
    if (s.contains("\\u")) {
        StringBuffer sUnescaped = new StringBuffer();
        Matcher m = unescapePattern.matcher(s);
        while (m.find() == true) {
            String slashes = m.group(1);
            String digits = m.group(3);
            int escapeCode;
            try {
                escapeCode = Integer.parseInt(digits, 16);
            } catch (NumberFormatException nfe) {
                /*
                 * the static regular expression string should guarantee
                 * that this exception is never thrown
                 */
                System.err.println("Impossible error: escape sequence '" + digits
                        + "' is not a valid hex number!  " + "Exception: " + nfe.toString());
                return s;
            }
            if (slashes != null && slashes.length() % 2 == 0 && isInvalidXMLCharacter(escapeCode)) {
                Character escapedSequence = Character.valueOf((char) escapeCode);
                /*
                 * slashes are apparently escaped when the string buffer is
                 * converted to a string, so double them to make sure the
                 * correct number appear in the final representation
                 */
                m.appendReplacement(sUnescaped, slashes + slashes + escapedSequence.toString());
            }
        }
        m.appendTail(sUnescaped);
        s = sUnescaped.toString();
    }
    return StringEscapeUtils.unescapeXml(s);
}

From source file:org.carewebframework.maven.plugin.processor.AbstractProcessor.java

/**
 * Adjust any url references in the line to use new root path.
 * // ww  w  . j a v a2 s.c o m
 * @param line String to modify
 * @return the modified string
 */
public String replaceURLs(String line) {
    StringBuffer sb = new StringBuffer();
    Matcher matcher = URL_PATTERN.matcher(line);
    String newPath = "~./" + getResourceBase() + "/";

    while (matcher.find()) {
        char dlm = line.charAt(matcher.start() - 1);
        int i = line.indexOf(dlm, matcher.end());
        String url = i > 0 ? line.substring(matcher.start(), i) : null;

        if (url == null || (!mojo.isExcluded(url) && getTransform(url) != null)) {
            matcher.appendReplacement(sb, newPath);
        }
    }

    matcher.appendTail(sb);
    return sb.toString();
}

From source file:hudson.plugins.emailext.plugins.content.BuildLogRegexContent.java

String getContent(BufferedReader reader) throws IOException {

    final boolean asHtml = matchedLineHtmlStyle != null;
    escapeHtml = asHtml || escapeHtml;/*from   w  w  w.ja va  2 s. co  m*/

    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:com.meidusa.venus.validate.validator.ValidatorSupport.java

public String getMessage(Object value) {
    if (message == null) {
        return "";
    }//from w  ww.ja va 2  s. c  o m
    String result = null;
    if (messageParameters == null || messageParameters.length == 0) {
        result = message;
    } else {
        Object[] parsedParameters = new Object[messageParameters.length];
        for (int i = 0; i < this.messageParameters.length; i++) {
            if (STAND_FOR_NAME.equals(messageParameters[i])) {
                parsedParameters[i] = this.describeValidateName();
            } else if (STAND_FOR_VALUE.equals(messageParameters[i])) {
                if (value != null) {
                    parsedParameters[i] = value.toString();
                } else {
                    parsedParameters[i] = "null";

                }
            } else {
                parsedParameters[i] = holder.findString(messageParameters[i]);
            }
        }
        result = String.format(message, parsedParameters);
    }
    Matcher matcher = validatorPattern.matcher(result);
    StringBuffer sb = new StringBuffer();
    Object obj = null;
    while (matcher.find()) {
        try {
            obj = PropertyUtils.getProperty(this, matcher.group(1));
        } catch (Exception e) {
            obj = "null";
        }
        if (obj == null) {
            obj = "null";
        }
        matcher.appendReplacement(sb, obj.toString());
    }
    matcher.appendTail(sb);
    return sb.toString();
}

From source file:org.opencastproject.composer.impl.AbstractCmdlineEmbedderEngine.java

/**
 * Builds command list out of template command by substituting input parameters in form #{&lt;parameter&gt;} with
 * values from properties. If for some parameter there is no matching value, parameter is removed. Parameters that are
 * set via switches are represented as #{&lt;switch&gt; &lt;key&gt;}. Arrays of parameters are represented #&lt;
 * parameters(s) &gt;/* w  ww.  j a  va  2s  . c  o  m*/
 * 
 * @param properties
 *          map that contains key/values pairs for building command. Unused pairs are ignored.
 * @return built list that represents command
 */
protected List<String> buildCommandFromTemplate(Map<String, String> properties) {

    // add binary
    List<String> commandList = new LinkedList<String>();
    commandList.add(binary);

    // process command line
    StringBuffer buffer = new StringBuffer();
    // process array parameters
    Pattern pattern = Pattern.compile("#<.+?>");
    Matcher matcher = pattern.matcher(cmdTemplate);
    while (matcher.find()) {
        String processedArray = buildArrayCommandFromTemplate(
                cmdTemplate.substring(matcher.start() + 2, matcher.end() - 1), properties);
        matcher.appendReplacement(buffer, processedArray);
    }
    matcher.appendTail(buffer);
    String arrayProcessedCmd = buffer.toString();
    // process normal parameters
    buffer = new StringBuffer();
    pattern = Pattern.compile("#\\{.+?\\}");
    matcher = pattern.matcher(arrayProcessedCmd);
    while (matcher.find()) {
        String match = arrayProcessedCmd.substring(matcher.start() + 2, matcher.end() - 1);
        if (match.contains(" ")) {
            String value = properties.get(match.split(" ")[1].trim());
            if (value == null) {
                matcher.appendReplacement(buffer, "");
            } else {
                matcher.appendReplacement(buffer, match.split(" ")[0] + " " + value);
            }
        } else {
            String value = properties.get(match.trim());
            if (value == null) {
                matcher.appendReplacement(buffer, "");
            } else {
                matcher.appendReplacement(buffer, value);
            }
        }
    }
    matcher.appendTail(buffer);

    // split and convert to array list
    String[] cmdArray = buffer.toString().split(" ");
    for (String e : cmdArray) {
        if (!"".equals(e))
            commandList.add(e);
    }

    return commandList;
}

From source file:org.eclim.plugin.jdt.command.doc.GetElementDocCommand.java

@Override
public Object execute(CommandLine commandLine) throws Exception {
    IJavaElement[] elements = null;/*from  ww  w .j a v a 2 s. com*/
    Object url = commandLine.getRawValue(Options.URL_OPTION);
    if (url != null) {
        IJavaElement target = JavaElementLinks.parseURI(new URI((String) url));
        if (target != null) {
            elements = new IJavaElement[] { target };
        }
    } else {
        String project = commandLine.getValue(Options.PROJECT_OPTION);
        String file = commandLine.getValue(Options.FILE_OPTION);
        int offset = getOffset(commandLine);
        int length = commandLine.getIntValue(Options.LENGTH_OPTION);

        ICompilationUnit src = JavaUtils.getCompilationUnit(project, file);
        elements = src.codeSelect(offset, length);
    }

    if (elements == null || elements.length == 0) {
        return null;
    }

    Method getHoverInfo = JavadocHover.class.getDeclaredMethod("getHoverInfo", IJavaElement[].class,
            ITypeRoot.class, IRegion.class, JavadocBrowserInformationControlInput.class);
    getHoverInfo.setAccessible(true);
    JavadocBrowserInformationControlInput info = (JavadocBrowserInformationControlInput) getHoverInfo
            .invoke(null, elements, null, null, null);
    if (info == null) {
        return null;
    }

    if (commandLine.hasOption(Options.HTML_OPTION)) {
        return info.getHtml();
    }

    ArrayList<HashMap<String, String>> links = new ArrayList<HashMap<String, String>>();
    Matcher matcher = LINKS.matcher(info.getHtml());
    StringBuffer buffer = new StringBuffer();
    int index = 0;
    while (matcher.find()) {
        String href = matcher.group(2);
        String text = matcher.group(3);
        HashMap<String, String> link = new HashMap<String, String>();
        link.put("href", href);
        link.put("text", text);
        links.add(link);
        matcher.appendReplacement(buffer, "|$3[" + (index++) + "]|");
    }
    matcher.appendTail(buffer);

    String html = buffer.toString();
    String result = IOUtils.toString(new HTML2TextReader(
            new StringReader(html != null ? html : StringUtils.EMPTY), new TextPresentation()));
    // remove \r for windows
    result = result.replaceAll("\r", "");
    // compact excessive spacing between sig and doc.
    result = result.replaceFirst("\n\n\n", "\n\n");

    HashMap<String, Object> response = new HashMap<String, Object>();
    response.put("text", result);
    response.put("links", links);
    return response;
}

From source file:org.kuali.ole.docstore.service.IngestNIndexHandlerService_UT.java

@Ignore
@Test/*from   w  w w .  j  a  v  a2s .  co m*/
public final void testMarcIngestWithSpecialChars() {
    List<String> bibIds = new ArrayList<String>();
    List<String> instanceIds = new ArrayList<String>();
    try {

        URL resource = getClass().getResource("/org/kuali/ole/repository/request.xml");
        File file = new File(resource.toURI());
        String input = FileUtils.readFileToString(file);
        StringBuffer stringBuffer = new StringBuffer();
        String regex = "Sandburg, Carl";
        String replace = "San~X1< 9+&!5#%^,&*(2)>{6}[8]!?H";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(input);
        while (matcher.find()) {
            matcher.appendReplacement(stringBuffer, replace);
        }
        matcher.appendTail(stringBuffer);
        String inputFile = stringBuffer.toString();
        RequestHandler rh = new RequestHandler();
        Request request = rh.toObject(inputFile);
        Response response = ingestNIndexHandlerService.ingestNIndexRequestDocuments(request);
        for (ResponseDocument resDoc : response.getDocuments()) {
            bibIds.add(resDoc.getUuid());
            for (ResponseDocument linkedDoc : resDoc.getLinkedDocuments()) {
                instanceIds.add(linkedDoc.getUuid());
            }
        }
        LOG.info("Bib Ids:" + bibIds);
        LOG.info("Instance ids:" + instanceIds);
        CheckoutManager checkoutManager = new CheckoutManager();
        for (String bibId : bibIds) {
            String checkedOutContent = checkoutManager.checkOut(bibId, "mockUser", "checkout");
            LOG.info("Bib Id:" + bibId);
            LOG.info("checkedOutContent for Bibliographic " + checkedOutContent);
        }
        for (String instanceId : instanceIds) {
            String checkedOutContent = checkoutManager.checkOut(instanceId, "mockUser", "checkout");
            LOG.info("Instance Id:" + instanceId);
            LOG.info("checkedOutContent fro Instance " + checkedOutContent);
        }

    } catch (Exception e) {
        LOG.info(e.getMessage(), e);
    }
}

From source file:org.olat.modules.fo.archiver.formatters.ForumStreamedRTFFormatter.java

/**
 * /*from  ww  w.j  a  va  2 s.  c om*/
 * @param originalText
 * @return
 */
private String convertHTMLMarkupToRTF(String originalText) {
    String htmlText = originalText;

    Matcher mb = PATTERN_HTML_BOLD.matcher(htmlText);
    StringBuffer bolds = new StringBuffer();
    while (mb.find()) {
        mb.appendReplacement(bolds, "{\\\\b $1} ");
    }
    mb.appendTail(bolds);
    htmlText = bolds.toString();

    Matcher mi = PATTERN_HTML_ITALIC.matcher(htmlText);
    StringBuffer italics = new StringBuffer();
    while (mi.find()) {
        mi.appendReplacement(italics, "{\\\\i $1} ");
    }
    mi.appendTail(italics);
    htmlText = italics.toString();

    Matcher mbr = PATTERN_HTML_BREAK.matcher(htmlText);
    StringBuffer breaks = new StringBuffer();
    while (mbr.find()) {
        mbr.appendReplacement(breaks, "\\\\line ");
    }
    mbr.appendTail(breaks);
    htmlText = breaks.toString();

    Matcher mofo = PATTERN_CSS_O_FOQUOTE.matcher(htmlText);
    StringBuffer foquotes = new StringBuffer();
    while (mofo.find()) {
        mofo.appendReplacement(foquotes, "\\\\line {\\\\i $1} {\\\\pard $2\\\\par}");
    }
    mofo.appendTail(foquotes);
    htmlText = foquotes.toString();

    Matcher mp = PATTERN_HTML_PARAGRAPH.matcher(htmlText);
    StringBuffer paragraphs = new StringBuffer();
    while (mp.find()) {
        mp.appendReplacement(paragraphs, "\\\\line $1 \\\\line");
    }
    mp.appendTail(paragraphs);
    htmlText = paragraphs.toString();

    Matcher mahref = PATTERN_HTML_AHREF.matcher(htmlText);
    StringBuffer ahrefs = new StringBuffer();
    while (mahref.find()) {
        mahref.appendReplacement(ahrefs,
                "{\\\\field{\\\\*\\\\fldinst{HYPERLINK\"$1\"}}{\\\\fldrslt{\\\\ul $2}}}");
    }
    mahref.appendTail(ahrefs);
    htmlText = ahrefs.toString();

    Matcher mli = PATTERN_HTML_LIST.matcher(htmlText);
    StringBuffer lists = new StringBuffer();
    while (mli.find()) {
        mli.appendReplacement(lists, "$1\\\\line ");
    }
    mli.appendTail(lists);
    htmlText = lists.toString();

    Matcher mtp = PATTERN_THREEPOINTS.matcher(htmlText);
    StringBuffer tps = new StringBuffer();
    while (mtp.find()) {
        mtp.appendReplacement(tps, THREEPOINTS);
    }
    mtp.appendTail(tps);
    htmlText = tps.toString();

    // strip all other html-fragments, because not convertable that easy
    htmlText = FilterFactory.getHtmlTagsFilter().filter(htmlText);
    // Remove all &nbsp;
    Matcher tmp = HTML_SPACE_PATTERN.matcher(htmlText);
    htmlText = tmp.replaceAll(" ");
    htmlText = StringEscapeUtils.unescapeHtml(htmlText);

    return htmlText;
}