Example usage for java.util.regex Matcher start

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

Introduction

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

Prototype

public int start() 

Source Link

Document

Returns the start index of the previous match.

Usage

From source file:com.sencha.gxt.core.rebind.XTemplateParser.java

public TemplateModel parse(String template) throws UnableToCompleteException {
    // look for parameters or tags (Consider combining into one pattern)
    TemplateModel model = new TemplateModel();
    Stack<ContainerTemplateChunk> stack = new Stack<ContainerTemplateChunk>();
    stack.push(model);/*w  w  w  . j  a v  a  2 s . c om*/
    Matcher m = NON_LITERAL_PATTERN.matcher(template);
    int lastMatchEnd = 0;
    while (m.find()) {
        // range of the current non-literal
        int begin = m.start(), end = m.end();
        String currentMatch = template.substring(begin, end);

        // if there was content since the last non-literal chunk, track it
        if (lastMatchEnd < begin) {
            ContentChunk c = literal(template.substring(lastMatchEnd, begin));
            stack.peek().children.add(c);
            log(c);
        }

        // move the last match pointer
        lastMatchEnd = end;

        // tpl tag starting
        Matcher tagOpenMatch = TAG_PATTERN.matcher(currentMatch);
        if (tagOpenMatch.matches()) {
            ControlChunk c = new ControlChunk();
            c.controls = new HashMap<String, String>();
            String attrs = tagOpenMatch.group(1).trim();
            Matcher attrMatcher = ATTR_PATTERN.matcher(attrs);
            while (attrMatcher.find()) {
                // should be if or for
                String key = attrMatcher.group(1);
                // must be html-decoded
                String encodedValue = attrMatcher.group(2) == null ? attrMatcher.group(3)
                        : attrMatcher.group(2);
                String value = StringEscapeUtils.unescapeXml(encodedValue);
                c.controls.put(key, value);
            }
            stack.peek().children.add(c);
            stack.push(c);
            log(c);
            continue;
        }

        // tpl tag ending
        Matcher tagCloseMatch = TAG_CLOSE_PATTERN.matcher(currentMatch);
        if (tagCloseMatch.matches()) {
            TemplateChunk c;
            try {
                c = stack.pop();
            } catch (EmptyStackException ex) {
                logger.log(Type.ERROR, "Too many </tpl> tags");
                throw new UnableToCompleteException();
            }
            log(c);
            continue;
        }

        // reference (code)
        Matcher codeMatch = INVOKE_PATTERN.matcher(currentMatch);
        if (codeMatch.matches()) {
            ContentChunk c = new ContentChunk();
            c.type = ContentType.CODE;
            c.content = codeMatch.group(1);
            stack.peek().children.add(c);
            log(c);
            continue;
        }

        // reference (param)
        Matcher paramMatch = PARAM_PATTERN.matcher(currentMatch);
        if (paramMatch.matches()) {
            ContentChunk c = new ContentChunk();
            c.type = ContentType.REFERENCE;
            c.content = paramMatch.group(1);
            stack.peek().children.add(c);
            log(c);
            continue;
        }
    }
    // handle trailing content
    if (lastMatchEnd < template.length()) {
        ContentChunk c = literal(template.substring(lastMatchEnd));
        log(c);
        model.children.add(c);
    }
    if (model != stack.peek()) {
        logger.log(Type.ERROR, "Too few </tpl> tags");
        throw new UnableToCompleteException();
    }
    return model;
}

From source file:org.sharextras.webscripts.connector.HttpOAuthConnector.java

/**
 * Percent-encode a parameter for construction of the base string and the Authorization header, 
 * as specified in http://tools.ietf.org/html/rfc5849#section-3.6
 * /*from w  ww  . j  av a2s . co  m*/
 * @param p Unencoded string
 * @return Encoded text
 */
private String encodeParameter(String p) {
    String encoded = URLEncoder.encodeUriComponent(p);

    StringBuffer sb = new StringBuffer(encoded.length());
    Pattern pattern = Pattern.compile("%[0-9a-f]{2}");
    Matcher m = pattern.matcher(encoded);
    int lastEnd = 0;
    while (m.find()) {
        sb.append(encoded.substring(lastEnd, m.start())).append(m.group().toUpperCase(Locale.ENGLISH));
        lastEnd = m.end();
    }
    sb.append(encoded.substring(lastEnd));
    return sb.toString().replaceAll("!", "%21").replaceAll("\\(", "%28").replaceAll("\\)", "%29")
            .replaceAll("\\*", "%2A");
}

From source file:de.micromata.genome.gwiki.plugin.confluenceimporter_1_0.confluence.ConfluenceImporter.java

protected String patchInternalLinks(GWikiContext wikiContext, String body, String pathPrefix) {
    String regexp = "\\[([^\n]+?)\\]";
    Pattern p = Pattern.compile(regexp);
    Matcher m = p.matcher(body);
    StringBuilder sb = new StringBuilder();
    int lastEnd = 0;
    while (m.find() == true) {
        int start = m.start();
        int end = m.end();
        sb.append(body.subSequence(lastEnd, start));
        String linkb = m.group(1);
        lastEnd = end;// ww  w  .j  av a  2  s  . co m
        sb.append("[").append(patchLinkBody(wikiContext, linkb, pathPrefix)).append("]");

    }
    sb.append(body.substring(lastEnd));
    return sb.toString();
}

From source file:es.uvigo.ei.sing.adops.views.TextFileViewer.java

private void updateSearch() {
    textArea.getHighlighter().removeAllHighlights();

    final String textToFind = txtSearch.getText();

    if (!textToFind.isEmpty()) {
        final String text = textArea.getText();

        if (this.chkRegularExpression.isSelected()) {
            try {
                final Pattern pattern = Pattern.compile(textToFind);
                this.txtSearch.setBackground(Color.WHITE);

                final Matcher matcher = pattern.matcher(text);

                while (matcher.find()) {
                    try {
                        textArea.getHighlighter().addHighlight(matcher.start(), matcher.end(),
                                highlightPatiner);
                    } catch (BadLocationException e1) {
                        e1.printStackTrace();
                    }/*from www.ja va  2 s .co m*/
                }
            } catch (PatternSyntaxException pse) {
                this.txtSearch.setBackground(Color.RED);
            }
        } else {
            final int textToFindLength = textToFind.length();

            int index = 0;
            while ((index = text.indexOf(textToFind, index)) != -1) {
                try {
                    textArea.getHighlighter().addHighlight(index, index + textToFindLength, highlightPatiner);
                    index += textToFindLength + 1;
                } catch (BadLocationException e1) {
                    e1.printStackTrace();
                }
            }
        }
    }
}

From source file:com.thomasjensen.checkstyle.addons.checks.misc.ModuleDirectoryLayoutCheck.java

@CheckForNull
DecomposedPath decomposePath(@Nonnull final String pFilePath) {
    String modulePath = "";
    String mdlPath = null;//from  w ww .j a  va 2  s  .  c om
    String specificPath = null;
    String simpleFilename = null;
    Set<String> fileExtensions = new HashSet<String>();
    List<String> specificFolders = new ArrayList<String>();

    if (!pFilePath.startsWith(baseDir.getPath())) {
        return null;
    }
    String filePath = cutSlashes(pFilePath.substring(baseDir.getPath().length()));

    if (moduleRegexp.pattern().length() > 0) {
        final Matcher matcher = moduleRegexp.matcher(filePath);
        if (matcher.find() && matcher.start() == 0) {
            modulePath = cutSlashes(matcher.group(0));
        } else {
            log(0, "moduledirectorylayout.invalid.module", filePath, moduleRegexp.pattern());
            return null;
        }
    }
    if (modulePath.length() > 0) {
        filePath = cutSlashes(filePath.substring(modulePath.length()));
    }

    for (final String mdlPathCandidate : mdlConfig.getStructure().keySet()) {
        if (filePath.startsWith(Util.standardizeSlashes(mdlPathCandidate))) {
            mdlPath = mdlPathCandidate;
            filePath = cutSlashes(filePath.substring(mdlPathCandidate.length()));
        }
    }
    if (mdlPath == null) {
        if (filePath.indexOf(File.separatorChar) > 0) { // no error if file is in module root
            log(0, "moduledirectorylayout.invalid.mdlpath", filePath);
        }
        return null;
    }

    specificPath = filePath;

    Matcher matcher = FILE_EXTENSION.matcher(filePath);
    if (matcher.find()) {
        String ext = matcher.group(1);
        for (int d = ext.lastIndexOf('.'); d > 0; d = ext.lastIndexOf('.', d - 1)) {
            fileExtensions.add(ext.substring(d + 1));
        }
        fileExtensions.add(ext);
    }

    int lastSlash = filePath.lastIndexOf(File.separatorChar);
    simpleFilename = filePath.substring(lastSlash + 1);

    String[] fragments = filePath.split("[\\\\/]");
    specificFolders.addAll(Arrays.asList(fragments).subList(0, fragments.length - 1));

    DecomposedPath result = new DecomposedPath(modulePath, mdlPath, specificPath, simpleFilename,
            fileExtensions, specificFolders);
    return result;
}

From source file:com.sangupta.pep.Generator.java

private SlideVariables getSlideVariables(String slideContents) {
    SlideVariables vars = new SlideVariables();

    Matcher matcher = PATTERN.matcher(slideContents);

    if (matcher != null && matcher.matches()) {
        vars.setHeader(matcher.group(1));
        vars.setLevel(Integer.valueOf(matcher.group(2)));
        vars.setTitle(matcher.group(3));
        vars.setContent(matcher.group(4));
    } else {/* w  ww  . j  a  v  a  2 s. c  o  m*/
        vars.setHeader("");
        vars.setTitle("");
        vars.setContent(slideContents);
        vars.setLevel(0);
    }

    // process slide classes
    ContentAndClasses cc = processMacros(vars);

    String content = cc.getContent();
    vars.setContent(content);
    vars.setClasses(cc.getClasses().toArray(new String[0]));

    if (StringUtils.isNotEmpty(content)) {
        content = content.trim();
        Pattern p2 = Pattern.compile("<h\\d[^>]*>presenter notes</h\\d>",
                Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE | Pattern.DOTALL);
        Matcher m2 = p2.matcher(content);

        if (m2 != null && m2.matches()) {
            vars.setPresenterNotes(content.substring(m2.end()).trim());
            content = content.substring(0, m2.start());

            vars.setContent(content);
        }
    }

    vars.setRelativeSourcePath(this.inputFile.getPath());
    vars.setAbsoluteSourcePath(this.inputFile.getAbsolutePath());

    return vars;
}

From source file:com.nextep.designer.sqlgen.ui.editors.SQLTextHtmlHover.java

@SuppressWarnings("unchecked")
@Override//from  w w  w.j  ava  2 s . co m
public String getHoverInfo(ITextViewer textViewer, IRegion hoverRegion) {
    final int offset = hoverRegion.getOffset();
    final IDocument document = textViewer.getDocument();
    if (document == null)
        return null;

    IRegion lineInfo;
    String line;
    try {
        lineInfo = document.getLineInformationOfOffset(offset);
        line = document.get(lineInfo.getOffset(), lineInfo.getLength());
    } catch (BadLocationException ex) {
        return null;
    }

    // Retrieving proposals
    ITypedObjectTextProvider provider = SQLEditorUIServices.getInstance().getTypedObjectTextProvider();
    List<String> allProposals = provider.listProvidedElements();
    for (String s : allProposals) {
        if (line.toUpperCase().contains(s.toUpperCase())) {
            // More accurate search
            Pattern p = Pattern.compile("(\\W|\\s|^)" + s.toUpperCase() + "(\\W|\\s|$)"); //$NON-NLS-1$ //$NON-NLS-2$
            Matcher m = p.matcher(line.toUpperCase());
            while (m.find()) {
                if (offset >= (m.start() + lineInfo.getOffset())
                        && offset <= (m.end() + lineInfo.getOffset())) {

                    final ITypedObject obj = provider.getElement(s);
                    final StringBuffer buf = new StringBuffer();
                    final INamedObject named = (INamedObject) obj;
                    buf.append("<html>"); //$NON-NLS-1$
                    addStyleSheet(buf);
                    appendColors(buf, FontFactory.BLACK.getRGB(), FontFactory.LIGHT_YELLOW.getRGB());
                    // buf.append("\n<table BORDER=0 BORDERCOLOR=\"#000000\" CELLPADDING=0 cellspacing=0 >\n");
                    // buf.append("<tr><td>\n");
                    URL u = ImageService.getInstance()
                            .getImageURL(ImageFactory.getImageDescriptor(obj.getType().getIcon()));
                    buf.append("<table border=0><tr valign=\"CENTER\"><td><img src=\"" //$NON-NLS-1$
                            + u.toExternalForm() + "\"/>&nbsp;"); //$NON-NLS-1$
                    buf.append("</td><td><b>" + obj.getType().getName() + " " + named.getName() //$NON-NLS-1$ //$NON-NLS-2$
                            + "</b></td></tr></table>"); //$NON-NLS-1$
                    if (named.getDescription() != null && !"".equals(named.getDescription().trim())) { //$NON-NLS-1$
                        buf.append("<i>" + named.getDescription() + "</i><br><br>"); //$NON-NLS-1$ //$NON-NLS-2$
                    } else {
                        buf.append("<i>"); //$NON-NLS-1$
                        buf.append(SQLMessages.getString("sqlHover.noDesc")); //$NON-NLS-1$
                        buf.append("</i><br><br>"); //$NON-NLS-1$
                    }
                    // Temporarily adding table definition here
                    if (obj instanceof IBasicTable) {
                        final IBasicTable t = (IBasicTable) obj;
                        buf.append("<table BORDER=1 BORDERCOLOR=\"#000000\" CELLPADDING=4 cellspacing=0 >\n"); // + //$NON-NLS-1$
                        buf.append("<tr bgcolor=\""); //$NON-NLS-1$
                        appendColor(buf, new RGB(220, 250, 220));
                        buf.append("\"><td><b>"); //$NON-NLS-1$
                        buf.append(SQLMessages.getString("sqlHover.columnNameCol")); //$NON-NLS-1$
                        buf.append("</b></td><td><b>"); //$NON-NLS-1$
                        buf.append(SQLMessages.getString("sqlHover.datatypeCol")); //$NON-NLS-1$
                        buf.append("</b></td><td><b>"); //$NON-NLS-1$
                        buf.append(SQLMessages.getString("sqlHover.descriptionCol")); //$NON-NLS-1$
                        buf.append("</b></td></tr>\n"); //$NON-NLS-1$
                        // /*cellspacing=\"0\" callpadding=\"0\" */  "border=\"1\" align=\"left\" width=\"350\">\n");
                        for (IBasicColumn c : t.getColumns()) {
                            buf.append("<tr>\n"); //$NON-NLS-1$
                            buf.append("<td>" + c.getName() + "</td>\n"); //$NON-NLS-1$ //$NON-NLS-2$
                            buf.append("<td>" + c.getDatatype() + "</td>\n"); //$NON-NLS-1$ //$NON-NLS-2$
                            final String desc = c.getDescription();
                            buf.append("<td>" + (desc == null ? "" : desc) + "</td>\n"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
                            buf.append("</tr>"); //$NON-NLS-1$
                        }
                        buf.append("</table><br>"); //$NON-NLS-1$
                    } else {
                        buf.append("<br>"); //$NON-NLS-1$
                    }
                    if (obj instanceof IReferencer) {
                        Collection<IReference> refs = ((IReferencer) obj).getReferenceDependencies();
                        if (refs != null && !refs.isEmpty()) {
                            buf.append("<b>"); //$NON-NLS-1$
                            buf.append(SQLMessages.getString("sqlHover.dependentOf")); //$NON-NLS-1$
                            buf.append("</b><br><span>"); //$NON-NLS-1$
                            for (IReference r : refs) {
                                IReferenceable ref = VersionHelper.getReferencedItem(r);
                                buf.append("<li>" + ((ITypedObject) ref).getType().getName() //$NON-NLS-1$
                                        + "&nbsp;<u>" + ((INamedObject) ref).getName() //$NON-NLS-1$
                                        + "</u></li>"); //$NON-NLS-1$
                                // buf.append(Designer.getInstance().getQualifiedName(ref)
                                // + "<br>");
                            }
                            buf.append("</span><br>"); //$NON-NLS-1$
                        }
                    }
                    if (obj instanceof IReferenceable && invRefMap != null) {
                        Collection<IReferencer> referencers = (Collection<IReferencer>) invRefMap
                                .get(((IReferenceable) obj).getReference());
                        if (referencers != null && !referencers.isEmpty()) {
                            buf.append("<b>"); //$NON-NLS-1$
                            buf.append(SQLMessages.getString("sqlHover.dependencies")); //$NON-NLS-1$
                            buf.append("</b><br><span>"); //$NON-NLS-1$
                            for (IReferencer r : referencers) {
                                buf.append("<li>" + ((ITypedObject) r).getType().getName() //$NON-NLS-1$
                                        + "&nbsp;<u>" + ((INamedObject) r).getName() //$NON-NLS-1$
                                        + "</u></li>"); //$NON-NLS-1$
                            }
                        }
                        buf.append("</span>"); //$NON-NLS-1$
                    }
                    // buf.append("</td></tr></table>");
                    buf.append("</body></html>"); //$NON-NLS-1$
                    return buf.toString();
                }
            }
        }
    }
    return null;
}

From source file:edu.cmu.lti.f12.hw2.hw2_team01.passage.SentenceBasedPassageCandidateFinder.java

public List<PassageCandidate> extractPassages(String[] keyterms) {
    // String[] paragraphs = text.split("<P>");
    List<PassageSpan> paragraphs = splitParagraph(text);
    int start = 0, end = 0;

    List<PassageSpan> matchedSpans = new ArrayList<PassageSpan>();
    List<PassageCandidate> passageList = new ArrayList<PassageCandidate>();
    // System.out.println("starting paragraph spans");
    Iterator<PassageSpan> iparagprah = paragraphs.iterator();
    String paragraph = new String();
    PassageSpan ps;/*from   w  w  w .  j a  v  a2 s  .co m*/

    for (String keyterm : keyterms) {
        Pattern p = Pattern.compile(keyterm.toLowerCase());
        Matcher m = p.matcher(text.toLowerCase());
        while (m.find()) {
            PassageSpan match = new PassageSpan(m.start(), m.end());
            matchedSpans.add(match);
            totalMatches++;
        }
        if (!matchedSpans.isEmpty()) {
            totalKeyterms++;
        }
    }

    while (iparagprah.hasNext()) {
        ps = iparagprah.next();
        paragraph = text.substring(ps.begin, ps.end);
        start = ps.begin;
        end = ps.end;
        // System.out.println("cleaning text...");
        String cleanText = Jsoup.parse(paragraph).text().replaceAll("([\177-\377\0-\32]*)", "");
        int keytermsFound = 0;
        int matchednum = 0;
        for (String keyterm : keyterms) {
            // System.out.println("matching keyterms...");
            Pattern p = Pattern.compile(keyterm.toLowerCase());
            Matcher mClean = p.matcher(cleanText.toLowerCase());
            while (mClean.find()) {
                PassageSpan match = new PassageSpan(mClean.start(), mClean.end());
                matchedSpans.add(match);
                matchednum++;
            }
            if (!matchedSpans.isEmpty()) {
                // matchingSpans.add(matchedSpans);
                keytermsFound++;
            }
        }
        if (matchednum != 0) {
            double score = scorer.scoreWindow(start, end, matchednum, totalMatches, keytermsFound,
                    totalKeyterms, textSize);

            try {
                BioPassageCandidate pc = new BioPassageCandidate(docId, start, end, (float) score, null);
                pc.keytermMatches = keytermsFound;
                pc.setText(paragraph);
                passageList.add(pc);

            } catch (AnalysisEngineProcessException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

    return passageList;
}

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

private String getContent(BufferedReader reader) throws IOException {
    final Pattern pattern = Pattern.compile(regex);
    final boolean asHtml = matchedSegmentHtmlStyle != null;
    escapeHtml = asHtml || escapeHtml;/*from   www .  j a v  a2  s  .  c  o m*/

    StringBuilder line = new StringBuilder();
    StringBuilder fullLog = new StringBuilder();
    int ch;
    // Buffer log contents including line terminators, and remove console notes
    while ((ch = reader.read()) != -1) {
        if (ch == '\r' || ch == '\n') {
            if (line.length() > 0) {
                // Remove console notes (JENKINS-7402)
                fullLog.append(ConsoleNote.removeNotes(line.toString()));
                line.setLength(0);
            }
            fullLog.append((char) ch);
        } else {
            line.append((char) ch);
        }
    }
    // Buffer the final log line if it has no line terminator
    if (line.length() > 0) {
        // Remove console notes (JENKINS-7402)
        fullLog.append(ConsoleNote.removeNotes(line.toString()));
    }
    StringBuilder content = new StringBuilder();
    int numMatches = 0;
    boolean insidePre = false;
    int lastMatchEnd = 0;
    final Matcher matcher = pattern.matcher(fullLog);
    while (matcher.find()) {
        if (maxMatches != 0 && ++numMatches > maxMatches) {
            break;
        }
        if (showTruncatedLines) {
            if (matcher.start() > lastMatchEnd) {
                // Append information about truncated lines.
                int numLinesTruncated = countLineTerminators(
                        fullLog.subSequence(lastMatchEnd, matcher.start()));
                if (numLinesTruncated > 0) {
                    insidePre = stopPre(content, insidePre);
                    appendLinesTruncated(content, numLinesTruncated, asHtml);
                }
            }
        }
        if (asHtml) {
            insidePre = startPre(content, insidePre);
        }
        if (substText != null) {
            final StringBuffer substBuf = new StringBuffer();
            matcher.appendReplacement(substBuf, substText);
            // Remove prepended text between matches
            final String segment = substBuf.substring(matcher.start() - lastMatchEnd);
            appendMatchedSegment(content, segment, escapeHtml, matchedSegmentHtmlStyle);
        } else {
            appendMatchedSegment(content, matcher.group(), escapeHtml, matchedSegmentHtmlStyle);
        }
        lastMatchEnd = matcher.end();
    }
    if (showTruncatedLines) {
        if (fullLog.length() > lastMatchEnd) {
            // Append information about truncated lines.
            int numLinesTruncated = countLineTerminators(fullLog.subSequence(lastMatchEnd, fullLog.length()));
            if (numLinesTruncated > 0) {
                insidePre = stopPre(content, insidePre);
                appendLinesTruncated(content, numLinesTruncated, asHtml);
            }
        }
    }
    stopPre(content, insidePre);
    return content.toString();
}