Example usage for java.util.regex MatchResult groupCount

List of usage examples for java.util.regex MatchResult groupCount

Introduction

In this page you can find the example usage for java.util.regex MatchResult groupCount.

Prototype

public int groupCount();

Source Link

Document

Returns the number of capturing groups in this match result's pattern.

Usage

From source file:de.mat.utils.pdftools.PdfMerge.java

/**
 * <h4>FeatureDomain:</h4>/* w w  w .  j a va 2 s . c  o  m*/
 *     PublishingTools
 * <h4>FeatureDescription:</h4>
 *     parse bookmarks from file
 * <h4>FeatureResult:</h4>
 *   <ul>
 *     <li>returnValue lstBookMarks - list of Bookmarks (Filename, Label...)
 *   </ul> 
 * <h4>FeatureKeywords:</h4>
 *     PDF Publishing
 * @param listFile - file with the Bookmarks
 * @return - list of Bookmarks
 * @throws Throwable
 */
public static List<Bookmark> parseBookMarksFromFile(String listFile) throws Throwable {
    // BookMarkliste aus Datei lesen
    List<Bookmark> lstBookMarks = new ArrayList<Bookmark>();
    String fileContent = readFromFile(listFile);
    String[] lines = fileContent.split("\n");
    if (lines != null) {
        // alle Zeilen durchlaufen
        for (int zaehler = 0; zaehler < lines.length; zaehler++) {
            // 
            String line = lines[zaehler];
            line = line.replace("\r", "");
            line = line.replace("\n", "");

            List<MatchResult> matches = findMatches(CONST_BOOKMARK, line);
            if (matches == null || matches.size() <= 0) {
                continue;
            }

            //iterate matches
            for (MatchResult match : matches) {

                // if found: add bookmark to list
                if (match.groupCount() == 4) {
                    Bookmark mpBookMark = new Bookmark();
                    String fileName = match.group(1);
                    fileName = fileName.replaceAll("\\+", "_");
                    fileName = fileName.replaceAll(">", "_");
                    mpBookMark.put("SRC", fileName);
                    mpBookMark.put("NAME", match.group(2));
                    mpBookMark.put("TYPE", match.group(3));
                    mpBookMark.put("PAGE", match.group(4));
                    lstBookMarks.add(mpBookMark);
                }
            }
        }
    }
    return lstBookMarks;
}

From source file:com.edgenius.wiki.render.RenderUtil.java

/**
 * Parse macro string and return macro name and its parameters. The value from key of WikiConstants.MACRO_NAME_KEY in return map 
 * is macro name then with its parameters. This input suppose only has one macro (the first is parse if there are multiple macro) 
 * and this macro doesn't  be check if esacped,i.e., like \{macor} also is treat as valid macro.  
 * If input hasn't valid macro, null is returned.
 * @param macro/*from   w  w  w. ja  va 2  s . c  o m*/
 * @return
 */
public static Map<String, String> parseSignleMacro(String macro) {
    if (StringUtils.isBlank(macro))
        return null;

    MatchResult rs = FilterRegxConstants.SINGLE_MACRO_FILTER_PATTERN.matcher(macro).toMatchResult();
    int count = rs.groupCount();
    if (count < 1)
        return null;

    Map<String, String> out = new HashMap<String, String>();
    out.put(WikiConstants.MACRO_NAME_KEY, rs.group(1));
    if (count > 1) {
        BaseMacroParameter params = new BaseMacroParameter();
        params.setParams(rs.group(2));
        out.putAll(params.getParams());
    }
    return out;
}

From source file:com.jaxio.celerio.template.VelocityGeneratorTest.java

@Test
public void testExtraction() {
    String message = "Object 'com.jaxio.celerio.convention.WellKnownFolder' does not contain property 'resource' at src/main/resources/spring/springmvc-parent.p.vm.xml[line "
            + "28, column 47]";
    Scanner s = new Scanner(message);
    String u = s.findInLine("\\[line (\\d+), column (\\d+)\\]");
    assertThat(u).isNotEmpty();/*from   w w w.  j a v  a 2  s.c o m*/
    MatchResult result = s.match();
    assertThat(result.groupCount()).isEqualTo(2);
    assertThat(result.group(1)).isEqualTo("28");
    assertThat(result.group(2)).isEqualTo("47");
}

From source file:com.edgenius.wiki.render.filter.UrlFilter.java

@Override
public void replace(StringBuffer buffer, MatchResult matchResult, RenderContext context) {
    int count = matchResult.groupCount();
    if (count != 2) {
        buffer.append(matchResult.group(0));
        return;/*from www  . jav a2s . c o m*/
    }

    String front = matchResult.group(1);
    String link = matchResult.group(2);
    String end = "";
    Matcher m = END_PATTERN.matcher(StringUtils.reverse(link));
    if (m.lookingAt()) {
        end = StringUtils.reverse(m.group(1));
        link = link.substring(0, link.length() - end.length());
    }

    buffer.append(formatter.format(new Object[] { front, link, end, RenderUtil.getExternalImage(context) }));

}

From source file:com.edgenius.wiki.render.filter.HeadingFilter.java

@SuppressWarnings("unchecked")
@Override/*from www .  j  a va2 s.  c  om*/
public void replace(StringBuffer buffer, MatchResult matchResult, RenderContext context) {
    int i = matchResult.groupCount();
    if (i < 3) {
        //failure tolerance
        buffer.append(matchResult.group(0));
        return;
    }
    String lead = matchResult.group(1);
    String level = matchResult.group(3);
    //please note this piece text should be regionKey rather than original text.
    String title = matchResult.group(4);

    String tail = matchResult.group(5);

    List<HeadingModel> list = (List<HeadingModel>) context.getGlobalParam(TOCMacro.class.getName());
    if (list == null) {
        list = new ArrayList<HeadingModel>();
        context.putGlobalParam(TOCMacro.class.getName(), list);
    }
    //put anchor data to RenderContext.global for later TOCMacro render (if page contain TOCMacro) 
    //The anchor must not change for each render - otherwise it is can not be redirect again once page refresh.
    String headerAnchor = "HeaderAnchor" + list.size();
    HeadingModel head = new HeadingModel();
    head.setOrder(context.createIncremetalKey());
    head.setLevel(NumberUtils.toInt(level));
    head.setTitle(title);
    head.setAnchor(headerAnchor);

    list.add(head);

    //group(2): number of heading, 
    buffer.append(formatter.format(new Object[] { lead, level, title, tail, headerAnchor }));
}

From source file:com.google.mr4c.util.CustomFormat.java

public Map<String, String> parse(String str) {
    if (!matches(str)) {
        throw new IllegalArgumentException(String.format("[%s] doesn't match pattern [%s]", str, m_pattern));
    }//  w w w  . j  a v a 2 s. co m
    Scanner scanner = new Scanner(str);
    scanner.findWithinHorizon(m_regex, 0);
    MatchResult result = scanner.match();
    Map<String, String> vals = new HashMap<String, String>();
    if (result.groupCount() != m_nameList.size()) {
        // this shouldn't be able to happen
        throw new IllegalStateException(
                String.format("[%s] doesn't match pattern [%s]; found %d matches, expected %d", str, m_pattern,
                        result.groupCount(), m_nameList.size()));
    }
    for (int i = 1; i <= result.groupCount(); i++) {
        String name = m_nameList.get(i - 1);
        String val = result.group(i);
        if (vals.containsKey(name)) {
            if (!vals.get(name).equals(val)) {
                throw new IllegalArgumentException(
                        String.format("[%s]doesnt match pattern [%s]; variable [%s] has values [%s] and [%s]",
                                str, m_pattern, name, val, vals.get(name)));
            }
        }
        vals.put(name, result.group(i));
    }
    return vals;
}

From source file:com.edgenius.wiki.render.filter.LinkFilter.java

@Override
public void replace(StringBuffer buffer, MatchResult result, RenderContext context) {
    int idx = result.groupCount();

    if (idx < 1) {
        // failure tolerance
        buffer.append(result.group(0));/*from  w w w . jav  a 2  s.c o  m*/
        return;
    }

    Region bodyRegion = context.getCurrentRegion();
    LinkModel model = getLinkModel(result, bodyRegion);

    LinkRenderHelper linkRenderHelper = context.getLinkRenderHelper();

    //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    //   Concatenate LINK URL
    String view = model.getView(), link = model.getLink(), anchor = model.getAnchor(),
            extSpaceUname = model.getSpaceUname();
    int type = model.getType();
    ObjectPosition pos = null;
    if (LinkUtil.isExtLink(link)) {
        // if it start from "http://" etc. start, it is extlink

        //use ObjectPosition rather than direct render to String, is for link surrounding content
        //for example, [!image.jpg!>http://www.edgenius.com], the !image.jpg! can render as well
        pos = new ObjectPosition(result.group(0));
        pos.serverHandler = LinkHandler.HANDLER;
        pos.uuid = context.createUniqueKey(false);
        pos.values = new HashMap<String, String>();
        //if it is [view>http://foo.com] format, view will be reset in subRegion()
        pos.values.put(NameConstants.VIEW, view);
        //Please note, NameConstants.NAME won't be set!!! See LinkFilter, it treats if(name==null) as extlink format.
        context.getObjectList().add(pos);

        //here will make LinkHandler process content part beside <a>, ie, <a>content</a>
        model.setView(pos.uuid);

        //model view is pos.uuid now, will replace in subRegion render.
        buffer.append(linkRenderHelper.getExternalImage(context, link));
        buffer.append(model.toRichAjaxTag());

    } else {
        if (extSpaceUname != null) {
            if (!linkRenderHelper.exists(extSpaceUname, link)) {
                //does not allow create new page from outside space. here only show link break image.
                buffer.append(linkRenderHelper.getExtspaceLinkBreakImage(context));
            }
            if (anchor != null) {
                pos = linkRenderHelper.appendExtSpaceLink(buffer, extSpaceUname, link, view, anchor);
            } else {
                pos = linkRenderHelper.appendExtSpaceLink(buffer, extSpaceUname, link, view);
            }
        } else {
            //if link is blank, maybe anchor only format(redir in same page) [view>#anchor] 
            if (type == LinkModel.LINK_TO_ATTACHMENT) {
                //file attachment link
                pos = new ObjectPosition(result.group(0));
                pos.serverHandler = LinkHandler.HANDLER;
                pos.uuid = context.createUniqueKey(false);
                pos.values.put(NameConstants.VIEW, view);
                //remove leading "^"
                pos.values.put(NameConstants.NAME, link.substring(1));
                pos.values.put(NameConstants.TYPE, String.valueOf(LinkModel.LINK_TO_ATTACHMENT));
                context.getObjectList().add(pos);
                buffer.append(pos.uuid);

            } else if (StringUtils.isBlank(link) || linkRenderHelper.exists(link)
            //if web service or RSS request, then return page always return valid even the page doesn't exist.
            //For example, shell request the page, it doesn't want to the non-exist page link block back javascript
            //it may want to display 404 error.
                    || RenderContext.RENDER_TARGET_PLAIN_VIEW.equals(context.getRenderTarget())) {
                // Do not add hash if an alias was given
                if (anchor != null) {
                    pos = linkRenderHelper.appendLink(buffer, link, view, anchor);
                } else {
                    pos = linkRenderHelper.appendLink(buffer, link, view);
                }
            } else if (linkRenderHelper.showCreate()) {
                buffer.append(linkRenderHelper.getNonexistImage(context));
                pos = linkRenderHelper.appendCreateLink(buffer, link, view);
                // links with "create" are not cacheable because
                // a missing wiki could be created
                // context.getRenderContext().setCacheable(false);
            } else {
                // cannot display/create wiki, so just display the text
                pos = new ObjectPosition(result.group(0));
                pos.serverHandler = LinkHandler.HANDLER;
                pos.uuid = context.createUniqueKey(false);
                pos.values.put(NameConstants.VIEW, view);
                pos.values.put(NameConstants.NAME, link);
                //this flag will tell LinkHandler "PageNotFound, But no permission to create page" - comparing with external link, ie, http:// etc.
                pos.values.put(NameConstants.TYPE, String.valueOf(LinkModel.LINK_TO_READONLY));
                context.getObjectList().add(pos);
                buffer.append(pos.uuid);
            }
        }
    }

    if (bodyRegion != null && bodyRegion.getSubRegion() != null && pos != null) {
        bodyRegion.getSubRegion().setKey(pos.uuid);
    }
}

From source file:com.edgenius.wiki.render.filter.UserFilter.java

@Override
public void replace(StringBuffer buffer, MatchResult result, RenderContext context) {
    if (context.getCurrentRegion() == null) {
        AuditLogger.error("Unexpected case: Immutable fitler cannot find out current region." + result.group());
    }//from w  w w.  j a  va 2  s.  co m

    String content = context.getCurrentRegion() != null ? context.getCurrentRegion().getContent()
            : result.group(2);
    String username = content;

    StringBuffer sb = new StringBuffer(result.group(1));

    if (!StringUtils.isBlank(username)) {
        HashMap<String, String> attValues = new HashMap<String, String>();
        username = username.trim();

        attValues.put(NameConstants.NAME, username);

        //this image scr will be handler after all page finish scan to HTML
        ObjectPosition userPos = new ObjectPosition(result.group(0));
        userPos.uuid = context.createUniqueKey(false);
        userPos.serverHandler = HANDLER;
        userPos.values = attValues;
        context.getObjectList().add(userPos);
        sb.append(userPos.uuid);

        buffer.append(sb);

        //append tailed text after filter
        if (result.groupCount() > 2)
            buffer.append(result.group(3));
    } else {
        //if only "@@" in page, do nothing
        buffer.append(result.group(0));
    }

}

From source file:com.edgenius.wiki.render.filter.MacroFilter.java

private void handleMacro(boolean paired, StringBuffer buffer, MatchResult result, RenderContext context,
        List<Region> pairRegions, String startTagBody) {
    //don't eat first character, which is checking for Escape "\"
    //result group: 1-macro name, 2-parameter, 3-surrounding content
    String macroName = result.group(1);

    if (macroName != null) {
        // {$peng} are variables not macros.
        if (!macroName.startsWith("$")) {
            try {
                Macro macro = macroMgr.getMacro(macroName);
                if (macro.isPaired() != paired) {
                    String body = result.group(0);
                    int start = buffer.length();
                    int end = start + body.length();
                    Region pair = new Region(start, end);
                    //no parameter, then mark as unknown, otherwise, must be a start macro
                    if (StringUtils.isBlank(result.group(2))) {
                        pair.setKey(MACRO_REGION_KEY_UNKNOWN);
                    } else {
                        pair.setKey(MACRO_REGION_KEY_START);
                    }/*from w w w. ja va  2  s . c om*/
                    pair.setContent(macroName);
                    pair.setBody(body);
                    //sum into list
                    pairRegions.add(pair);

                    buffer.append(body);
                    return;
                }

                BaseMacroParameter mParams = new BaseMacroParameter();
                mParams.setMacroName(macroName);
                mParams.setRenderContext(context);

                switch (result.groupCount()) {
                case 3:
                    if (macro instanceof ImmutableContentMacro) {
                        if (context.getCurrentRegion() == null) {
                            AuditLogger
                                    .error("Unexpected case: Immutable fitler cannot find out current region."
                                            + result.group());
                        }

                        mParams.setContent(
                                context.getCurrentRegion() != null ? context.getCurrentRegion().getContent()
                                        : result.group(3));
                    } else {
                        mParams.setContent(result.group(3));
                    }
                    //no break!
                case 2:
                    //parameter won't be HTML entity format. And macro parameter value slash unescape will do while 
                    //parameter parsed, inside MacroParameter.setParams().
                    mParams.setParams(StringEscapeUtil.unescapeHtml(result.group(2)));
                }

                // recursively filter macros within macros
                if (macro.isProcessEmbedded() && mParams.getContent() != null) {
                    mParams.setContent(filter(mParams.getContent(), context));
                }

                if (mParams.getContent() == null)
                    mParams.setContent("");

                //if paired markup, the startTagBody is parsed from filter beginning singleMarkupParser...
                //for single markup, then just the whole text.
                mParams.setStartMarkup(paired ? startTagBody : result.group(0));

                macro.execute(buffer, mParams);
            } catch (MalformedMacroException e) {
                buffer.append(
                        RenderUtil.renderError("Invalid macro: " + e.getMessage(), result.group(0)).toString());
            } catch (Throwable e) {
                log.warn("MacroFilter: unable to format macro: " + result.group(0));
                buffer.append(result.group(0));
                return;
            }
        } else {
            // {$peng}, so far, do nothing for this format
            buffer.append(result.group(0));
        }
    } else {
        //unable to parse out correct macro name, render original String
        buffer.append(result.group(0));
    }
}

From source file:com.edgenius.wiki.render.filter.ImageFilter.java

@Override
public void replace(StringBuffer buffer, MatchResult result, RenderContext context) {
    String src;/*from  w  ww.  j  a  va2 s .  c  o m*/
    Region bodyRegion = context.getCurrentRegion();
    if (bodyRegion != null) {
        src = bodyRegion.getContent();
    } else {
        AuditLogger.error("Unexpected case: Immutable fitler cannot find out current region." + result.group());
        src = result.group(1);
    }

    HashMap<String, String> attValues = new HashMap<String, String>();
    //append leading text before the real markup !image.png!
    StringBuffer sb = new StringBuffer(result.group(1));

    if (src != null && src.trim().length() > 0) {
        src = src.trim();

        //there are some other attributes, such as float
        String[] split = StringUtil.splitWithoutEscaped(src, "|");
        //as splitwidhtouEscaped() always return non-zero length String[], 
        //ie, if there is "|" then return input string as first element of string[], so it is safe to check split[0]
        src = split[0];

        for (int idx = 1; idx < split.length; idx++) {
            String att = split[idx].trim();
            if (SharedConstants.ALIGN_VALUES.contains(att)) {
                attValues.put(ALIGN, att);
            } else if (SharedConstants.SIZE_VALUES.contains(att)) {
                if (StringUtil.equalsIgnoreCase(SharedConstants.SIZE_VALUES.big.getName(), att)
                        || StringUtil.equalsIgnoreCase(SharedConstants.SIZE_VALUES.large.getName(), att)) {
                    // large thumbnail
                    attValues.put(WIDTH, ImageModel.LARGE_THUMBNAIL_WIDTH);
                } else {
                    // small thumbnail
                    attValues.put(WIDTH, ImageModel.SMALL_THUMBNAIL_WIDTH);
                }
            } else {
                if (att.indexOf("=") != -1) {
                    String[] pair = att.split("=");
                    if (pair.length == 2) {
                        attValues.put(pair[0], EscapeUtil.removeSlashEscape(pair[1]));
                    }
                } else {
                    //is it xxx * yyy ?
                    String[] wh = att.split("\\*");
                    if (wh.length == 2) {
                        int w = NumberUtils.toInt(wh[0], -1);
                        int h = NumberUtils.toInt(wh[1], -1);
                        if (w != -1 && h != -1) {
                            attValues.put(WIDTH, "" + w);
                            attValues.put(HEIGHT, "" + h);
                        }
                    }
                }
            }
        }

        attValues.put(SRC, src);
        //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        // NOTE: always user ImageHandler rather that simple append "http://image-file-url" 
        // after buffer. The reason is image file name may be any, for example, my--pic--1.jpg,
        // if append to buffer, file name will replace by StrightThrough filter! 
        ObjectPosition pos = new ObjectPosition(result.group(0));
        pos.uuid = context.createUniqueKey(false);
        pos.serverHandler = HANDLER;
        pos.values = attValues;
        context.getObjectList().add(pos);
        sb.append(pos.uuid);
        buffer.append(sb);

        if (bodyRegion != null && bodyRegion.getSubRegion() != null && pos != null) {
            bodyRegion.getSubRegion().setKey(pos.uuid);
        }

        //append tailed text after markup
        if (result.groupCount() > 2)
            buffer.append(result.group(3));
        return;
    } else {
        //TODO need i18n
        buffer.append(RenderUtil.renderError("Image filter needs src attribute to declare the image URL.",
                result.group(0)));
    }
}