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:eu.mihosoft.vrl.fxscad.MainController.java

/**
 * Initializes the controller class./*from ww w.j a  va2 s. c  om*/
 *
 * @param url
 * @param rb
 */
@Override
public void initialize(URL url, ResourceBundle rb) {

    //
    codeArea.textProperty().addListener((ov, oldText, newText) -> {
        Matcher matcher = KEYWORD_PATTERN.matcher(newText);
        int lastKwEnd = 0;
        StyleSpansBuilder<Collection<String>> spansBuilder = new StyleSpansBuilder<>();
        while (matcher.find()) {
            spansBuilder.add(Collections.emptyList(), matcher.start() - lastKwEnd);
            spansBuilder.add(Collections.singleton("keyword"), matcher.end() - matcher.start());
            lastKwEnd = matcher.end();
        }
        spansBuilder.add(Collections.emptyList(), newText.length() - lastKwEnd);
        codeArea.setStyleSpans(0, spansBuilder.create());
    });

    EventStream<Change<String>> textEvents = EventStreams.changesOf(codeArea.textProperty());

    textEvents.reduceSuccessions((a, b) -> b, Duration.ofMillis(500)).subscribe(code -> {
        if (autoCompile) {
            compile(code.getNewValue());
        }
    });

    codeArea.replaceText("CSG cube = new Cube(2).toCSG()\n" + "CSG sphere = new Sphere(1.25).toCSG()\n" + "\n"
            + "cube.difference(sphere)");

    editorContainer.setContent(codeArea);

    subScene = new SubScene(viewGroup, 100, 100, true, SceneAntialiasing.BALANCED);

    subScene.widthProperty().bind(viewContainer.widthProperty());
    subScene.heightProperty().bind(viewContainer.heightProperty());

    PerspectiveCamera subSceneCamera = new PerspectiveCamera(false);
    subScene.setCamera(subSceneCamera);

    viewContainer.getChildren().add(subScene);
}

From source file:org.jspringbot.keyword.db.DbHelper.java

private String sqlSubstitute(String queryString) {
    StringBuilder buf = new StringBuilder(queryString);

    Matcher matcher = NAMED_PARAMETER_PATTERN.matcher(buf);

    int index = 0;
    while (matcher.find(index)) {
        String param = matcher.group().substring(1);
        if (literalSubstitution.containsKey(param)) {
            String replacement = literalSubstitution.get(param);
            buf.replace(matcher.start(), matcher.end(), replacement);

            index = matcher.start() + replacement.length();
        } else {//from www .java 2  s . c  o m
            index = matcher.end();
        }
    }

    return buf.toString();
}

From source file:com.nttec.everychan.chans.sevenchan.SevenchanReader.java

@Override
protected void parseThumbnail(String imgTag) {
    if (imgTag.contains("class=\"multithumbfirst\"") || imgTag.contains("class=\"multithumb\"")) {
        if (currentAttachments.size() > 0) {
            AttachmentModel attachment = currentAttachments.get(currentAttachments.size() - 1);
            int start, end;
            if ((start = imgTag.indexOf("src=\"")) != -1 && (end = imgTag.indexOf('\"', start + 5)) != -1)
                attachment.thumbnail = imgTag.substring(start + 5, end);

            Matcher byteSizeMatcher = ATTACHMENT_SIZE_PATTERN.matcher(imgTag);
            while (byteSizeMatcher.find()) {
                try {
                    String digits = byteSizeMatcher.group(1);
                    int multiplier = 1;
                    String prefix = byteSizeMatcher.group(2);
                    if (prefix != null) {
                        if (prefix.equalsIgnoreCase("k"))
                            multiplier = 1024;
                        else if (prefix.equalsIgnoreCase("m"))
                            multiplier = 1024 * 1024;
                    }//from www .  j av  a 2 s . com
                    int value = Math.round(Float.parseFloat(digits) / 1024 * multiplier);
                    attachment.size = value;
                } catch (NumberFormatException e) {
                }
            }

            Matcher pxSizeMatcher = ATTACHMENT_PX_SIZE_PATTERN.matcher(imgTag);
            int indexEndPxSize = -1;
            while (pxSizeMatcher.find()) {
                try {
                    int width = Integer.parseInt(pxSizeMatcher.group(1));
                    int height = Integer.parseInt(pxSizeMatcher.group(2));
                    attachment.width = width;
                    attachment.height = height;
                    indexEndPxSize = pxSizeMatcher.end();
                } catch (NumberFormatException e) {
                }
            }

            if (indexEndPxSize != -1) {
                Matcher originalNameMatcher = ATTACHMENT_ORIGINAL_NAME_PATTERN.matcher(imgTag);
                if (originalNameMatcher.find(indexEndPxSize)) {
                    String originalName = originalNameMatcher.group(1).trim();
                    if (originalName != null && originalName.length() > 0) {
                        attachment.originalName = StringEscapeUtils.unescapeHtml4(originalName);
                    }
                }
            }

        }
    } else if (imgTag.contains("/css/locked.gif")) {
        currentThread.isClosed = true;
    } else if (imgTag.contains("/css/sticky.gif")) {
        currentThread.isSticky = true;
    } else {
        int start, end;
        if ((start = imgTag.indexOf("src=\"")) != -1 && (end = imgTag.indexOf('\"', start + 5)) != -1)
            lastThumbnail = imgTag.substring(start + 5, end);
    }
}

From source file:de.ingrid.mdek.dwr.services.HttpService.java

public String parseHtml(String url, int maxWords) {
    // Parse the given url and return a string with maxWords
    StringBean sb = new StringBean();
    sb.setLinks(false);//w  w w  .j  a v a 2  s .  c o m
    sb.setReplaceNonBreakingSpaces(true);
    sb.setCollapse(true);
    sb.setURL(url);
    String str = sb.getStrings(); // fetch url contents to str

    /*
          // NOTE: First approach was trying to use a regexp to find the first n words in a string.
          // Surprisingly, this is way too slow for n > 15.
          // We now use a more simple regexp and just match it n times.
            
           // Extract the first n words from str
           // Pattern consists of '(word+word_boundary...)*maxWords'
           // The flag DOTALL is required so newlines are also matched by '.'
           Pattern expression = Pattern.compile("^(\\w+\\b.*?){"+maxWords+"}", Pattern.DOTALL);
           Pattern expression = Pattern.compile("^(\\w+\\b\\s*?){"+maxWords+"}");
           Matcher matcher = expression.matcher(str);
           // If the first n words are found, return the match. Otherwise just return str.
           if (matcher.lookingAt()) {
              return matcher.group();
           } else {
              return str;
           }
    */
    // regexp for 'word+word_boundary+{whitespace}'
    Pattern expression = Pattern.compile("\\w+\\b\\s*?");
    Matcher matcher = expression.matcher(str);

    // Try to find the expression 'maxWords' times.
    // If the expression is not found (most likely due to the input string containing less than maxWords words),
    // the flag noMatch will be set.
    boolean noMatch = false;
    for (int i = 0; i < maxWords; ++i) {
        if (!matcher.find()) {
            noMatch = true;
            break;
        }
    }

    if (noMatch || maxWords < 1) {
        // str contains less than maxWords words. Just return it.
        return str;
    } else {
        // str contains more than maxWords words. Return a substring till the end of the last match.
        return str.substring(0, matcher.end());
    }
}

From source file:com.semperos.screwdriver.js.LessSource.java

private void resolveImports() throws FileNotFoundException, IOException {
    Matcher importMatcher = IMPORT_PATTERN.matcher(normalizedContent);
    while (importMatcher.find()) {
        String importedFile = importMatcher.group(3);
        importedFile = importedFile.matches(".*\\.(le?|c)ss$") ? importedFile : importedFile + ".less";
        boolean css = importedFile.matches(".*css$");
        if (!css) {
            LessSource importedLessSource = new LessSource(new File(file.getParentFile(), importedFile));
            imports.put(importedFile, importedLessSource);
            normalizedContent = normalizedContent.substring(0, importMatcher.start())
                    + importedLessSource.getNormalizedContent()
                    + normalizedContent.substring(importMatcher.end());
            importMatcher = IMPORT_PATTERN.matcher(normalizedContent);
        }/*from  w  ww .ja  v  a2s.  com*/
    }
}

From source file:com.ficeto.esp.EspExceptionDecoder.java

private void parseText() {
    String content = inputArea.getText();
    Pattern p = Pattern.compile("40[0-2](\\d|[a-f]){5}\\b");
    int count = 0;
    Matcher m = p.matcher(content);
    while (m.find()) {
        count++;// ww  w . j  a v a 2  s. com
    }
    if (count == 0) {
        return;
    }
    String command[] = new String[4 + count];
    int i = 0;
    command[i++] = tool.getAbsolutePath();
    command[i++] = "-aipfC";
    command[i++] = "-e";
    command[i++] = elf.getAbsolutePath();
    m = p.matcher(content);
    while (m.find()) {
        command[i++] = content.substring(m.start(), m.end());
    }
    outputText += "<i>Decoding " + count + " results</i>\n";
    sysExec(command);
}

From source file:com.microsoft.azure.keyvault.test.CertificateOperationsTest.java

/**
 * Extracts certificates from PEM contents
 * //from   w w w  .  j  a  v  a2  s. co  m
 * @throws CertificateException
 * @throws IOException
 */
private static List<X509Certificate> extractCertificatesFromPemContents(String pemContents)
        throws CertificateException, IOException {
    Matcher matcher = _certificate.matcher(pemContents);
    if (!matcher.find()) {
        throw new IllegalArgumentException("No certificate found in PEM contents.");
    }

    List<X509Certificate> result = new ArrayList<X509Certificate>();
    int offset = 0;
    while (true) {
        if (!matcher.find(offset)) {
            break;
        }
        byte[] certBytes = _base64.decode(matcher.group(1));
        ByteArrayInputStream certStream = new ByteArrayInputStream(certBytes);
        CertificateFactory certificateFactory = CertificateFactory.getInstance(X509);
        X509Certificate x509Certificate = (X509Certificate) certificateFactory.generateCertificate(certStream);
        certStream.close();

        result.add(x509Certificate);
        offset = matcher.end();
    }

    return result;
}

From source file:ch.njol.skript.command.Commands.java

@Nullable
public final static ScriptCommand loadCommand(final SectionNode node) {
    final String key = node.getKey();
    if (key == null)
        return null;
    final String s = ScriptLoader.replaceOptions(key);

    int level = 0;
    for (int i = 0; i < s.length(); i++) {
        if (s.charAt(i) == '[') {
            level++;//w  w w  .  j a  v  a  2s .co m
        } else if (s.charAt(i) == ']') {
            if (level == 0) {
                Skript.error("Invalid placement of [optional brackets]");
                return null;
            }
            level--;
        }
    }
    if (level > 0) {
        Skript.error("Invalid amount of [optional brackets]");
        return null;
    }

    Matcher m = commandPattern.matcher(s);
    final boolean a = m.matches();
    assert a;

    final String command = "" + m.group(1).toLowerCase();
    final ScriptCommand existingCommand = commands.get(command);
    if (existingCommand != null && existingCommand.getLabel().equals(command)) {
        final File f = existingCommand.getScript();
        Skript.error("A command with the name /" + command + " is already defined"
                + (f == null ? "" : " in " + f.getName()));
        return null;
    }

    final String arguments = m.group(3) == null ? "" : m.group(3);
    final StringBuilder pattern = new StringBuilder();

    List<Argument<?>> currentArguments = new ArrayList<Argument<?>>();
    m = argumentPattern.matcher(arguments);
    int lastEnd = 0;
    int optionals = 0;
    for (int i = 0; m.find(); i++) {
        pattern.append(escape("" + arguments.substring(lastEnd, m.start())));
        optionals += StringUtils.count(arguments, '[', lastEnd, m.start());
        optionals -= StringUtils.count(arguments, ']', lastEnd, m.start());

        lastEnd = m.end();

        ClassInfo<?> c;
        c = Classes.getClassInfoFromUserInput("" + m.group(2));
        final NonNullPair<String, Boolean> p = Utils.getEnglishPlural("" + m.group(2));
        if (c == null)
            c = Classes.getClassInfoFromUserInput(p.getFirst());
        if (c == null) {
            Skript.error("Unknown type '" + m.group(2) + "'");
            return null;
        }
        final Parser<?> parser = c.getParser();
        if (parser == null || !parser.canParse(ParseContext.COMMAND)) {
            Skript.error("Can't use " + c + " as argument of a command");
            return null;
        }

        final Argument<?> arg = Argument.newInstance(m.group(1), c, m.group(3), i, !p.getSecond(),
                optionals > 0);
        if (arg == null)
            return null;
        currentArguments.add(arg);

        if (arg.isOptional() && optionals == 0) {
            pattern.append('[');
            optionals++;
        }
        pattern.append("%" + (arg.isOptional() ? "-" : "")
                + Utils.toEnglishPlural(c.getCodeName(), p.getSecond()) + "%");
    }

    pattern.append(escape("" + arguments.substring(lastEnd)));
    optionals += StringUtils.count(arguments, '[', lastEnd);
    optionals -= StringUtils.count(arguments, ']', lastEnd);
    for (int i = 0; i < optionals; i++)
        pattern.append(']');

    String desc = "/" + command + " ";
    final boolean wasLocal = Language.setUseLocal(true); // use localised class names in description
    try {
        desc += StringUtils.replaceAll(pattern, "(?<!\\\\)%-?(.+?)%", new Callback<String, Matcher>() {
            @Override
            public String run(final @Nullable Matcher m) {
                assert m != null;
                final NonNullPair<String, Boolean> p = Utils.getEnglishPlural("" + m.group(1));
                final String s = p.getFirst();
                return "<" + Classes.getClassInfo(s).getName().toString(p.getSecond()) + ">";
            }
        });
    } finally {
        Language.setUseLocal(wasLocal);
    }
    desc = unescape(desc);
    desc = "" + desc.trim();

    node.convertToEntries(0);
    commandStructure.validate(node);
    if (!(node.get("trigger") instanceof SectionNode))
        return null;

    final String usage = ScriptLoader.replaceOptions(node.get("usage", desc));
    final String description = ScriptLoader.replaceOptions(node.get("description", ""));
    ArrayList<String> aliases = new ArrayList<String>(
            Arrays.asList(ScriptLoader.replaceOptions(node.get("aliases", "")).split("\\s*,\\s*/?")));
    if (aliases.get(0).startsWith("/"))
        aliases.set(0, aliases.get(0).substring(1));
    else if (aliases.get(0).isEmpty())
        aliases = new ArrayList<String>(0);
    final String permission = ScriptLoader.replaceOptions(node.get("permission", ""));
    final String permissionMessage = ScriptLoader.replaceOptions(node.get("permission message", ""));
    final SectionNode trigger = (SectionNode) node.get("trigger");
    if (trigger == null)
        return null;
    final String[] by = ScriptLoader.replaceOptions(node.get("executable by", "console,players"))
            .split("\\s*,\\s*|\\s+(and|or)\\s+");
    int executableBy = 0;
    for (final String b : by) {
        if (b.equalsIgnoreCase("console") || b.equalsIgnoreCase("the console")) {
            executableBy |= ScriptCommand.CONSOLE;
        } else if (b.equalsIgnoreCase("players") || b.equalsIgnoreCase("player")) {
            executableBy |= ScriptCommand.PLAYERS;
        } else {
            Skript.warning(
                    "'executable by' should be either be 'players', 'console', or both, but found '" + b + "'");
        }
    }

    if (!permissionMessage.isEmpty() && permission.isEmpty()) {
        Skript.warning("command /" + command + " has a permission message set, but not a permission");
    }

    if (Skript.debug() || node.debug())
        Skript.debug("command " + desc + ":");

    final File config = node.getConfig().getFile();
    if (config == null) {
        assert false;
        return null;
    }

    Commands.currentArguments = currentArguments;
    final ScriptCommand c;
    try {
        c = new ScriptCommand(config, command, "" + pattern.toString(), currentArguments, description, usage,
                aliases, permission, permissionMessage, executableBy, ScriptLoader.loadItems(trigger));
    } finally {
        Commands.currentArguments = null;
    }

    registerCommand(c);

    if (Skript.logVeryHigh() && !Skript.debug())
        Skript.info("registered command " + desc);
    currentArguments = null;
    return c;
}

From source file:com.sbcc.edu.jrollspellchecker.MainWindow.java

private void indexTest(ArrayList<IndexedWord> indexedWords, int startIndex) {
    String regex = "\\w*";
    Pattern p = Pattern.compile(regex);

    //System.out.println("Text is : " + spellCheckText.getText());
    Matcher matcher = p.matcher(spellCheckText.getText());
    while (matcher.find()) {
        System.out.println("Starting & ending  index of" + matcher.group() + ":=" + "start=" + matcher.start()
                + " end = " + matcher.end());
        if (matcher.start() >= startIndex)
            indexedWords.add(new IndexedWord(matcher.start(), matcher.end(), matcher.group()));
    }//from  ww w .j  a va  2  s  .  co m
}

From source file:de.dfki.km.perspecting.obie.model.Document.java

/***************************************************************************
 * Gets the pure plain text out of a html text. All html tags are replaced
 * by spaces. To do so, the head is replaced, all remaining javascript tags
 * (including the content) and finally all remaining html tags. Thus,
 * absolute positioning is possible./*from   ww w . j a  v  a 2s  .  c o  m*/
 * 
 * @param text
 *            content of the html document as text
 * @return text where all html was replaced by spaces
 */
private String extractPlainTextFromHtml(String text) {
    Collection<Pattern> patterns = new ArrayList<Pattern>(3);
    // Delete the head, then all remaining javascript items that might exist
    // in the body, then all remaining html tags.
    patterns.add(
            Pattern.compile("<head.*/head>", Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE | Pattern.DOTALL));
    // .*? makes it non greedy -> take the shortes match
    // DOTALL does also include new lines
    patterns.add(Pattern.compile("<script.*?/script>",
            Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE | Pattern.DOTALL));
    patterns.add(Pattern.compile("<.+?>", Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE));
    StringBuffer s = new StringBuffer(text);

    // Go for all patterns.
    for (Pattern p : patterns) {
        Matcher matcher = p.matcher(s);

        // As long as the matcher finds another occurance of the pattern we
        // replace it by the same number of spaces but keep new lines.
        while (matcher.find())
            s.replace(matcher.start(), matcher.end(), matcher.group().replaceAll(".", " "));
    }
    return s.toString();
}