Example usage for java.util.regex Matcher end

List of usage examples for java.util.regex Matcher end

Introduction

In this page you can find the example usage for java.util.regex Matcher end.

Prototype

public int end() 

Source Link

Document

Returns the offset after the last character matched.

Usage

From source file:com.heliosdecompiler.helios.gui.view.editors.DisassemblerView.java

private static StyleSpans<Collection<String>> computeHighlighting(String text) {
    Matcher matcher = PATTERN.matcher(text);
    int lastKwEnd = 0;
    StyleSpansBuilder<Collection<String>> spansBuilder = new StyleSpansBuilder<>();
    while (matcher.find()) {
        String styleClass = matcher.group("KEYWORD") != null ? "keyword"
                : matcher.group("PAREN") != null ? "paren"
                        : matcher.group("BRACE") != null ? "brace"
                                : matcher.group("BRACKET") != null ? "bracket"
                                        : matcher.group("SEMICOLON") != null ? "semicolon"
                                                : matcher.group("STRING") != null ? "string"
                                                        : matcher.group("COMMENT") != null ? "comment"
                                                                : null; /* never happens */
        assert styleClass != null;
        spansBuilder.add(Collections.emptyList(), matcher.start() - lastKwEnd);
        spansBuilder.add(Collections.singleton(styleClass), matcher.end() - matcher.start());
        lastKwEnd = matcher.end();/*from  w ww  . ja  va  2  s .  com*/
    }
    spansBuilder.add(Collections.emptyList(), text.length() - lastKwEnd);
    return spansBuilder.create();
}

From source file:de.csw.ontology.XWikiTextEnhancer.java

/**
 * Extract from text all phrases that are enclosed by '[' and ']' denoting
 * an xWiki link./* ww  w  .  j av  a  2  s .  c om*/
 * 
 * @param text
 *            text to parse
 */
protected void initializeLinkIndex(String text) {
    if (text == null)
        throw new NullPointerException("Parameter text must not be null");

    linkIndex.clear();

    if (text.isEmpty())
        return;

    for (Pattern pattern : EXCLUDE_FROM_ENHANCEMENTS) {
        Matcher matcher = pattern.matcher(text);
        while (matcher.find()) {
            linkIndex.put(matcher.start(), matcher.end());
        }
    }
}

From source file:Main.java

/**
 * Converts a given message from CTCP escaping.
 *
 * @param message message to convert//from   w w w.j a v  a 2 s. c  o m
 * @return converted message
 */
static String fromCTCP(String message) {
    message = message.substring(1); // Strip the starting delimiter
    message = message.substring(0, message.indexOf(CTCP_DELIMITER)); // Strip the second delimiter
    StringBuilder builder = new StringBuilder();
    int currentIndex = 0;
    Matcher matcher = CTCP_ESCAPED_CHAR.matcher(message);
    while (matcher.find()) {
        if (matcher.start() > currentIndex) {
            builder.append(message.substring(currentIndex, matcher.start()));
        }
        switch (matcher.group(1)) {
        case CTCP_MQUOTE + "":
            switch (matcher.group(2)) {
            case "n":
                builder.append('\n');
                break;
            case "r":
                builder.append('\r');
                break;
            case "0":
                builder.append('\u0000');
                break;
            default:
                builder.append(matcher.group(2)); // If not one of the above, disregard the MQUOTE. If MQUOTE, it's covered here anyway.
            }
            break;
        case "\\":
            switch (matcher.group(2)) {
            case "a":
                builder.append(CTCP_DELIMITER);
                break;
            default:
                builder.append(matcher.group(2)); // If not one of the above, disregard the \. If \, it's covered here anyway.
            }
        }
        currentIndex = matcher.end();
    }
    if (currentIndex < message.length()) {
        builder.append(message.substring(currentIndex));
    }
    return builder.toString();
}

From source file:net.sf.jabref.gui.fieldeditors.JTextAreaWithHighlighting.java

/**
 * Highlight words in the Textarea/* ww w.j  a  v  a2s  . c o m*/
 *
 * @param words to highlight
 */
private void highLight() {
    // highlight all characters that appear in charsToHighlight
    Highlighter highlighter = getHighlighter();
    highlighter.removeAllHighlights();

    if ((highlightPattern == null) || !highlightPattern.isPresent()) {
        return;
    }
    String content = getText();
    if (content.isEmpty()) {
        return;
    }

    highlightPattern.ifPresent(pattern -> {
        Matcher matcher = pattern.matcher(content);
        while (matcher.find()) {
            try {
                highlighter.addHighlight(matcher.start(), matcher.end(), DefaultHighlighter.DefaultPainter);
            } catch (BadLocationException ble) {
                // should not occur if matcher works right
                LOGGER.warn("Highlighting not possible, bad location", ble);
            }
        }
    });

}

From source file:org.esigate.parser.Parser.java

/**
 * Parses all the CharSequence./*from   w ww  . j ava  2 s .  co m*/
 * 
 * @param in
 *            The CharSequence to parse
 * @param out
 *            The Writable to write the result to
 * @throws IOException
 * @throws HttpErrorPage
 */
public void parse(CharSequence in, Appendable out) throws IOException, HttpErrorPage {
    ParserContextImpl ctx = new ParserContextImpl(out, httpRequest, httpResponse);
    Matcher matcher = pattern.matcher(in);
    int currentPosition = 0;
    while (matcher.find()) {
        String tag = matcher.group();
        ctx.characters(in, currentPosition, matcher.start());
        currentPosition = matcher.end();
        if (ctx.isCurrentTagEnd(tag)) {
            // check if this is the end tag for current element
            LOG.info("Processing end tag {}", tag);
            ctx.endElement(tag);
        } else {
            // if not, it is an opening tag for a new element
            LOG.info("Processing start tag {}", tag);
            ElementType type = null;
            for (ElementType t : elementTypes) {
                if (t.isStartTag(tag)) {
                    type = t;
                    break;
                }
            }
            Element element = type.newInstance();
            ctx.startElement(type, element, tag);
            if (type.isSelfClosing(tag)) {
                ctx.endElement(tag);
            }

        }
    }
    // we reached the end of input
    ctx.characters(in, currentPosition, in.length());
}

From source file:org.ops4j.pax.web.itest.karaf.WebJSFKarafTest.java

@Test
public void testJSF() throws Exception {

    LOG.info("Testing JSF workflow!");
    String response = testClient.testWebPath("http://127.0.0.1:8181/war-jsf-sample", "Please enter your name");

    LOG.info("Found JSF starting page: {}", response);
    int indexOf = response.indexOf("id=\"javax.faces.ViewState\" value=");
    String substring = response.substring(indexOf + 34);
    indexOf = substring.indexOf("\"");
    substring = substring.substring(0, indexOf);

    Pattern pattern = Pattern.compile("(input id=\"mainForm:j_id_\\w*)");
    Matcher matcher = pattern.matcher(response);
    if (!matcher.find())
        fail("Didn't find required input id!");

    String inputID = response.substring(matcher.start(), matcher.end());
    inputID = inputID.substring(inputID.indexOf('"') + 1);
    LOG.info("Found ID: {}", inputID);

    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
    nameValuePairs.add(new BasicNameValuePair("mainForm:name", "Dummy-User"));

    nameValuePairs.add(new BasicNameValuePair("javax.faces.ViewState", substring.trim()));
    nameValuePairs.add(new BasicNameValuePair(inputID, "Press me"));
    nameValuePairs.add(new BasicNameValuePair("mainForm_SUBMIT", "1"));

    LOG.info("Will send the following NameValuePairs: {}", nameValuePairs);

    testClient.testPost("http://127.0.0.1:8181/war-jsf-sample/faces/helloWorld.jsp", nameValuePairs,
            "Hello Dummy-User. We hope you enjoy Apache MyFaces", 200);

}

From source file:it.cnr.icar.eric.client.admin.AdminShellUtility.java

public String normalizeArgs(String args) {
    /*//from ww w . j av a 2s.c o  m
     * Pattern is choice of:
     *  - '"' (not preceded by '\') followed zero or more of:
     *     - Not a '"' or
     *     - '\"'
     *  - '"' that is preceded by '\'
     *  - Not a '"'
     */
    Pattern p = Pattern.compile("(?<!\\\\)\"(([^\"]|\\\\\")*)\"|(?<=\\\\)\"|[^\"]+");

    Matcher m = p.matcher(args);

    String matcherUseArgs = "";

    int prevEnd = 0;
    while (m.find()) {
        prevEnd = m.end();

        log.debug(rb.getString(AdminShell.ADMIN_SHELL_RESOURCES_PREFIX + "debug.group",
                new Object[] { m.group() }));
        String quotedString = m.group(1);

        if (quotedString != null) {
            matcherUseArgs += quotedString.replaceAll(" ", "\\\\ ");
            log.debug(rb.getString(AdminShell.ADMIN_SHELL_RESOURCES_PREFIX + "debug.quoted",
                    new Object[] { quotedString.replaceAll(" ", "\\\\ ") }));
        } else {
            matcherUseArgs += m.group();
            log.debug(rb.getString(AdminShell.ADMIN_SHELL_RESOURCES_PREFIX + "debug.unquoted",
                    new Object[] { m.group() }));
        }
    }

    if (prevEnd < args.length()) {
        String remainder = args.substring(prevEnd);
        log.debug(rb.getString(AdminShell.ADMIN_SHELL_RESOURCES_PREFIX + "debug.remainder",
                new Object[] { remainder }));

        if (remainder.matches(".*(?<!\\\\)\".*")) {
            log.debug(rb.getString(AdminShell.ADMIN_SHELL_RESOURCES_PREFIX + "unbalancedQuotes"));
        } else {
            matcherUseArgs += remainder;
        }
    }

    log.debug(rb.getString(AdminShell.ADMIN_SHELL_RESOURCES_PREFIX + "debug.matcher",
            new Object[] { matcherUseArgs }));

    String useArgs = args;

    String[] useArgsArray = useArgs.split("(?<=^|[^\\\\])\"", -1);

    useArgs = useArgsArray[0];

    if (log.isDebugEnabled()) {
        log.debug(args);

        for (int i = 0; i < useArgsArray.length; i++) {
            log.debug(useArgsArray[i] + ":");
        }
        log.debug("");
    }

    if ((useArgsArray.length > 1)) {
        // An even number of quotes results in an odd-number array length
        if (useArgsArray.length % 2 == 0) {
            log.error(rb.getString(AdminShell.ADMIN_SHELL_RESOURCES_PREFIX + "unbalancedQuotes"));
            return null;
        }

        for (int i = 1; i < useArgsArray.length; i += 2) {
            useArgsArray[i] = useArgsArray[i].replaceAll(" ", "\\\\ ");
        }

        for (int i = 1; i < useArgsArray.length; i++) {
            useArgs += useArgsArray[i];
        }
    }

    useArgs = useArgs.replaceAll("\\\\\"", "\"");
    useArgs = useArgs.replaceAll("\\\\ ", " ");

    if (log.isDebugEnabled()) {
        log.debug(":" + useArgs + ":");
    }

    return useArgs;
}

From source file:com.reprezen.swagedit.editor.hyperlinks.PathParamHyperlinkDetector.java

@Override
protected IHyperlink[] doDetect(SwaggerDocument doc, ITextViewer viewer, HyperlinkInfo info,
        JsonPointer pointer) {/*from  w ww. ja va  2  s  .  co  m*/
    // find selected parameter
    Matcher matcher = PARAMETER_PATTERN.matcher(info.text);
    String parameter = null;
    int start = 0, end = 0;
    while (matcher.find() && parameter == null) {
        if (matcher.start() <= info.column && matcher.end() >= info.column) {
            parameter = matcher.group(1);
            start = matcher.start();
            end = matcher.end();
        }
    }

    // no parameter found
    if (emptyToNull(parameter) == null) {
        return null;
    }

    Iterable<JsonPointer> targetPaths = findParameterPath(doc, pointer, parameter);

    IRegion linkRegion = new Region(info.getOffset() + start, end - start);
    List<IHyperlink> links = new ArrayList<>();
    for (JsonPointer path : targetPaths) {
        IRegion target = doc.getRegion(path);

        if (target != null) {
            links.add(new SwaggerHyperlink(parameter, viewer, linkRegion, target));
        }
    }

    return links.isEmpty() ? null : links.toArray(new IHyperlink[links.size()]);
}

From source file:com.norconex.importer.handler.tagger.impl.TextStatisticsTagger.java

@Override
protected void tagTextDocument(String reference, Reader input, ImporterMetadata metadata, boolean parsed)
        throws ImporterHandlerException {
    long charCount = 0;
    long wordCharCount = 0;
    long wordCount = 0;
    long sentenceCount = 0;
    long sentenceCharCount = 0;
    long paragraphCount = 0;

    //TODO make this more efficient, by doing all this in one pass.
    LineIterator it = IOUtils.lineIterator(input);
    while (it.hasNext()) {
        String line = it.nextLine().trim();
        if (StringUtils.isBlank(line)) {
            continue;
        }/*from   w  w w .j av a 2s  .c  om*/

        // Paragraph
        paragraphCount++;

        // Character
        charCount += line.length();

        // Word
        Matcher matcher = PATTERN_WORD.matcher(line);
        while (matcher.find()) {
            int wordLength = matcher.end() - matcher.start();
            wordCount++;
            wordCharCount += wordLength;
        }

        // Sentence
        BreakIterator boundary = BreakIterator.getSentenceInstance();
        boundary.setText(line);
        int start = boundary.first();
        for (int end = boundary.next(); end != BreakIterator.DONE; start = end, end = boundary.next()) {
            sentenceCharCount += (end - start);
            sentenceCount++;
        }
    }

    String field = StringUtils.EMPTY;
    if (StringUtils.isNotBlank(fieldName)) {
        field = fieldName.trim() + ".";
    }

    //--- Add fields ---
    metadata.addLong("document.stat." + field + "characterCount", charCount);
    metadata.addLong("document.stat." + field + "wordCount", wordCount);
    metadata.addLong("document.stat." + field + "sentenceCount", sentenceCount);
    metadata.addLong("document.stat." + field + "paragraphCount", paragraphCount);
    metadata.addString("document.stat." + field + "averageWordCharacterCount",
            divide(wordCharCount, wordCount));
    metadata.addString("document.stat." + field + "averageSentenceCharacterCount",
            divide(sentenceCharCount, sentenceCount));
    metadata.addString("document.stat." + field + "averageSentenceWordCount", divide(wordCount, sentenceCount));
    metadata.addString("document.stat." + field + "averageParagraphCharacterCount",
            divide(charCount, paragraphCount));
    metadata.addString("document.stat." + field + "averageParagraphSentenceCount",
            divide(sentenceCount, paragraphCount));
    metadata.addString("document.stat." + field + "averageParagraphWordCount",
            divide(wordCount, paragraphCount));

}

From source file:de.micromata.genome.gwiki.plugin.keywordsmarttags_1_0.GWikiFragmentKeywordHtml.java

protected void patch(KeyWordRanges kranges, String html,
        Map.Entry<String, Pair<Pattern, List<GWikiElementInfo>>> me) {
    if (StringUtils.isBlank(html) == true) {
        return;/*from ww  w.  j av  a2  s  . c o  m*/
    }
    Matcher m = me.getValue().getFirst().matcher(html);
    while (m.find() == true) {
        int sidx = m.start();
        int eidx = m.end();
        if (sidx != 0) {
            if (Character.isLetterOrDigit(html.charAt(sidx - 1)) == true) {
                continue;
            }
        }
        if (eidx < html.length() - 1) {
            if (Character.isLetterOrDigit(html.charAt(eidx)) == true) {
                continue;
            }
        }
        kranges.addIntersect(sidx, eidx, me.getValue().getSecond());
    }
}