Example usage for java.util.regex Matcher groupCount

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

Introduction

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

Prototype

public int groupCount() 

Source Link

Document

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

Usage

From source file:hudson.plugins.clearcase.ClearToolExec.java

private List<String> parseListOutput(Reader consoleReader, boolean onlyStarMarked) throws IOException {
    List<String> views = new ArrayList<String>();
    BufferedReader reader = new BufferedReader(consoleReader);
    String line = reader.readLine();
    while (line != null) {
        Matcher matcher = viewListPattern.matcher(line);
        if (matcher.find() && matcher.groupCount() == 3) {
            if ((!onlyStarMarked) || (onlyStarMarked && matcher.group(1).equals("*"))) {
                String vob = matcher.group(2);
                int pos = Math.max(vob.lastIndexOf('\\'), vob.lastIndexOf('/'));
                if (pos != -1) {
                    vob = vob.substring(pos + 1);
                }//from w ww. j  a v  a 2  s  . c o  m
                views.add(vob);
            }
        }
        line = reader.readLine();
    }
    reader.close();
    return views;
}

From source file:com.ephesoft.dcma.tablefinder.share.TableRowFinderUtility.java

/**
 * Method is responsible for finding the patterns and returned the found data List.
 * /*  ww w .  j  a va  2s.  co m*/
 * @param span Span
 * @param patternStr String
 * @return DataCarrier
 * @throws DCMAApplicationException Check for all the input parameters and find the pattern.
 */
private static final DataCarrier findPattern(final Span span, final String patternStr)
        throws DCMAApplicationException {

    String errMsg = null;
    DataCarrier dataCarrier = null;
    final CharSequence inputStr = span.getValue();
    if (null == inputStr || TableExtractionConstants.EMPTY.equals(inputStr)) {

        errMsg = "Invalid input character sequence.";
        LOGGER.info(errMsg);

    } else {

        if (null == patternStr || TableExtractionConstants.EMPTY.equals(patternStr)) {
            errMsg = "Invalid input pattern sequence.";
            throw new DCMAApplicationException(errMsg);
        }

        // Compile and use regular expression
        final Pattern pattern = Pattern.compile(patternStr);
        final Matcher matcher = pattern.matcher(inputStr);
        while (matcher.find()) {

            // Get all groups for this match
            for (int i = 0; i <= matcher.groupCount(); i++) {
                final String groupStr = matcher.group(i);
                List<Span> matchedSpans = null;
                if (groupStr != null) {
                    matchedSpans = new ArrayList<Span>();
                    matchedSpans.add(span);
                    String matchedString = PatternMatcherUtil.getMatchedSpansValue(matchedSpans);
                    if (!EphesoftStringUtil.isNullOrEmpty(matchedString)) {
                        final float confidence = (groupStr.length()
                                * CommonConstants.DEFAULT_MAXIMUM_CONFIDENCE) / matchedString.length();
                        dataCarrier = new DataCarrier(matchedSpans, confidence, matchedString, null);
                        LOGGER.info(groupStr);
                    }
                }
            }
        }
    }

    return dataCarrier;
}

From source file:com.temenos.interaction.media.hal.HALProvider.java

private String getEntityName(String resourcePath) throws MethodNotAllowedException {
    String entityName = null;/*  w  w w  . j a  v a 2  s  .  c o m*/

    if (resourcePath != null) {
        String absoluteUri = uriInfo.getBaseUri() + uriInfo.getPath();

        String tmpResourcePath = absoluteUri.substring(uriInfo.getBaseUri().toString().length());

        ResourceState state = getCurrentState(uriInfo.getBaseUri().toString(), tmpResourcePath);

        if (state != null) {
            entityName = state.getEntityName();
        } else {
            logger.warn("No state found, dropping back to path matching");
            Map<String, Set<String>> pathToResourceStates = resourceStateProvider.getResourceStatesByPath();
            for (String path : pathToResourceStates.keySet()) {
                for (String stateName : pathToResourceStates.get(path)) {
                    ResourceState s = resourceStateProvider.getResourceState(stateName);
                    String pathIdParameter = InteractionContext.DEFAULT_ID_PATH_ELEMENT;
                    if (s.getPathIdParameter() != null) {
                        pathIdParameter = s.getPathIdParameter();
                    }
                    Matcher matcher = Pattern.compile("(.*)\\{" + pathIdParameter + "\\}(.*)").matcher(path);
                    if (matcher.find()) {
                        int groupCount = matcher.groupCount();
                        if ((groupCount == 1 && resourcePath.startsWith(matcher.group(1)))
                                || (groupCount == 2 && resourcePath.startsWith(matcher.group(1))
                                        && resourcePath.endsWith(matcher.group(2)))) {
                            entityName = s.getEntityName();
                        }
                    }
                    if (entityName == null && path.startsWith(resourcePath)) {
                        entityName = s.getEntityName();
                    }
                }
            }
        }
    }

    return entityName;
}

From source file:com.moviejukebox.scanner.MediaInfoScanner.java

public String archiveScan(String movieFilePath) {
    if (!IS_ACTIVATED) {
        return null;
    }/*  ww  w. j  ava  2s . c om*/

    LOG.debug("Mini-scan on {}", movieFilePath);

    try {
        // Create the command line
        List<String> commandMedia = new ArrayList<>(MI_EXE);
        // Technically, mediaInfoExe has "-f" in it from above, but "-s" will override it anyway.
        // "-s" will dump just "$size $path" inside RAR/ISO.
        commandMedia.add("-s");
        commandMedia.add(movieFilePath);

        ProcessBuilder pb = new ProcessBuilder(commandMedia);

        // set up the working directory.
        pb.directory(MI_PATH);

        Process p = pb.start();

        String mediaArchive;
        try (BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()))) {
            String line;
            mediaArchive = null;
            while ((line = localInputReadLine(input)) != null) {
                Pattern patternArchive = Pattern.compile("^\\s*\\d+\\s(.*)$");
                Matcher m = patternArchive.matcher(line);
                if (m.find() && (m.groupCount() == 1)) {
                    mediaArchive = m.group(1);
                }
            }
        }

        LOG.debug("Returning with archivename {}", mediaArchive);

        return mediaArchive;

    } catch (IOException error) {
        LOG.error(SystemTools.getStackTrace(error));
    }

    return null;
}

From source file:hudson.plugins.clearcase.ClearToolExec.java

public Properties getViewData(String viewTag) throws IOException, InterruptedException {
    Properties resPrp = new Properties();
    ArgumentListBuilder cmd = new ArgumentListBuilder();
    cmd.add("lsview");
    cmd.add("-l", viewTag);

    Pattern uuidPattern = Pattern.compile("View uuid: (.*)");
    Pattern globalPathPattern = Pattern.compile("View server access path: (.*)");
    boolean res = true;
    IOException exception = null;
    List<IOException> exceptions = new ArrayList<IOException>();

    String output = runAndProcessOutput(cmd, null, null, true, exceptions);
    // handle the use case in which view doesn't exist and therefore error is thrown
    if (!exceptions.isEmpty() && !output.contains("No matching entries found for view")) {
        throw exceptions.get(0);
    }//  ww  w .j  av a2s . co m

    if (res && exception == null) {
        String[] lines = output.split("\n");
        for (String line : lines) {
            Matcher matcher = uuidPattern.matcher(line);
            if (matcher.find() && matcher.groupCount() == 1)
                resPrp.put("UUID", matcher.group(1));

            matcher = globalPathPattern.matcher(line);
            if (matcher.find() && matcher.groupCount() == 1)
                resPrp.put("STORAGE_DIR", matcher.group(1));
        }
    }

    return resPrp;
}

From source file:org.commonjava.vertx.vabr.ApplicationRouter.java

protected void parseParams(final BindingContext ctx, final HttpServerRequest request) {
    final Matcher matcher = ctx.getMatcher();

    final MultiMap params = new CaseInsensitiveMultiMap();

    final String fullPath = request.path();
    final String uri = requestUri(request);

    final PatternRouteBinding routeBinding = ctx.getPatternRouteBinding();
    final List<String> paramNames = routeBinding.getParamNames();
    final RouteBinding handler = routeBinding.getHandler();

    int i = 1;/*  w w w. j  av  a 2s . c  o  m*/

    if (matcher.groupCount() > 0) {
        final int firstIdx = matcher.start(i) + prefix.length();
        // be defensive in case the first param is optional...
        String routeBase = (firstIdx > 0) ? fullPath.substring(0, firstIdx) : fullPath;
        if (routeBase.endsWith("/")) {
            routeBase = routeBase.substring(0, routeBase.length() - 1);
        }

        params.add(BuiltInParam._routeBase.key(), routeBase);

        int idx = uri.indexOf(routeBase) + routeBase.length();
        final String routeContextUrl = uri.substring(0, idx);
        params.add(BuiltInParam._routeContextUrl.key(), routeContextUrl);

        idx = fullPath.indexOf(routeBase);

        String classBase = null;
        String classContext = null;
        if (idx > -1) {
            idx += routeBase.length();
            classBase = fullPath.substring(0, idx);
            params.add(BuiltInParam._classBase.key(), classBase);

            idx = uri.indexOf(routeBase) + routeBase.length();
            classContext = uri.substring(0, idx);
            params.add(BuiltInParam._classContextUrl.key(), classContext);
        }
    } else {
        final Class<?> handlerCls = handler.getHandlesClass();
        final Handles handles = handlerCls.getAnnotation(Handles.class);

        String pathPrefix = handles.value();
        if (isEmpty(pathPrefix)) {
            pathPrefix = handles.prefix();
        }

        final String find = pathPrefix.length() > 0 ? pathPrefix : prefix;
        int idx = fullPath.indexOf(find);

        String classBase = null;
        String classContext = null;
        if (idx > -1) {
            idx += find.length();
            classBase = fullPath.substring(0, idx);
            params.add(BuiltInParam._classBase.key(), classBase);

            idx = uri.indexOf(find) + find.length();
            classContext = uri.substring(0, idx);
            params.add(BuiltInParam._classContextUrl.key(), classContext);
        }
    }

    if (paramNames != null) {
        // Named params
        for (final String param : paramNames) {
            final String v = matcher.group(i);
            if (v != null) {
                logger.info("PARAM {} = {}", param, v);
                params.add(param, v);
            }
            i++;
        }
    }

    // Un-named params
    for (; i < matcher.groupCount(); i++) {
        final String v = matcher.group(i);
        if (v != null) {
            logger.info("PARAM param{} = {}", i, v);
            params.add("param" + i, v);
        }
    }

    final Query query = Query.from(request);
    for (final String name : paramNames) {
        params.add("q:" + name, query.getAll(name));
    }

    //        logger.info( "PARAMS: {}\n", params );
    request.params().add(params);
}

From source file:hudson.plugins.clearcase.ClearToolExec.java

/**
 * Work around for a CCase bug with hijacked directories:
 * in the case where a directory was hijacked, cleartool is not able to
 * remove it when it is not empty, we detect this and remove
 * the hijacked directories explicitly, then we relaunch the update.
 * @param viewPath/*w ww . j  a v  a2s  .c om*/
 * @param filePath
 * @param exceptions
 * @param output
 * @throws IOException
 * @throws InterruptedException
 */
private void handleHijackedDirectoryCCBug(String viewPath, FilePath filePath, List<IOException> exceptions,
        String output) throws IOException, InterruptedException {
    String[] lines = output.split("\n");
    int nbRemovedDirectories = 0;
    PrintStream logger = getLauncher().getListener().getLogger();
    for (String line : lines) {
        Matcher matcher = PATTERN_UNABLE_TO_REMOVE_DIRECTORY_NOT_EMPTY.matcher(line);
        if (matcher.find() && matcher.groupCount() == 1) {
            String directory = matcher.group(1);
            logger.println("Forcing removal of hijacked directory: " + directory);
            filePath.child(directory).deleteRecursive();
            nbRemovedDirectories++;
        }
    }
    if (nbRemovedDirectories == 0) {
        // Exception was unrelated to hijacked directories, throw it
        throw exceptions.get(0);
    } else {
        // We forced some hijacked directory removal, relaunch update
        logger.println("Relaunching update after removal of hijacked directories");
        update(viewPath, null);
    }
}

From source file:io.github.acashjos.anarch.RegexValueMatchBuilder.java

/**
 * Internal function/*from  ww w  . ja  v a  2 s  .  co m*/
 * Processes response body according to the matchbuilder specifications and returns JSONObject
 * @param responseText String on which the operations are to be conducted
 * @return JSONObject Object with all the extracted properties
 */
@Override
protected JSONObject processResponseText(String responseText) {
    JSONObject output = new JSONObject();

    for (PatternBlueprint test : patternSet) {
        Pattern p = Pattern.compile(test.pattern);
        Matcher m = p.matcher(responseText);

        JSONArray arr = new JSONArray();
        while (m.find()) {
            Log.v("debug", "find(): " + m.group());
            JSONObject single = test.once ? output : new JSONObject();

            //insers keys from mainTest
            for (Map.Entry<String, Integer> outkey : test.outputKeySet.entrySet()) {

                Log.v("debug", "outputkeyset: " + outkey.getKey());
                try {
                    single.put(outkey.getKey(), m.group(outkey.getValue()));
                } catch (JSONException e) {
                    e.printStackTrace();
                    continue;
                }
            }

            for (PatternBlueprint subtest : test.subPatternSet) {
                String patern = test.pattern;
                for (int i = 1; i <= m.groupCount(); ++i) {
                    patern = patern.replace("%" + i, m.group(i));
                }
                Pattern p2 = Pattern.compile(patern);
                Matcher m2 = p2.matcher(m.group(subtest.source_group));
                if (m2.find())
                    //insert keys from subtest
                    for (Map.Entry<String, Integer> outkey : subtest.outputKeySet.entrySet())
                        try {
                            single.put(outkey.getKey(), m2.group(outkey.getValue()));
                        } catch (JSONException e) {
                            e.printStackTrace();
                            continue;
                        }
            }
            if (!test.once) {
                arr.put(single);
            }

        }
        if (!test.once)
            try {
                output.put(test.id, arr);
            } catch (JSONException e) {
                continue;
            }

    }
    return output;
}

From source file:org.codehaus.groovy.grails.web.mapping.RegexUrlMapping.java

@SuppressWarnings("unchecked")
private UrlMappingInfo createUrlMappingInfo(String uri, Matcher m, int tokenCount) {
    boolean hasOptionalExtension = urlData.hasOptionalExtension();
    Map params = new HashMap();
    Errors errors = new MapBindingResult(params, "urlMapping");
    String lastGroup = null;/*w ww.j  ava  2s. c  om*/
    for (int i = 0, count = m.groupCount(); i < count; i++) {
        lastGroup = m.group(i + 1);
        // if null optional.. ignore
        if (i == tokenCount & hasOptionalExtension) {
            ConstrainedProperty cp = constraints[constraints.length - 1];
            cp.validate(this, lastGroup, errors);

            if (errors.hasErrors()) {
                return null;
            }

            params.put(cp.getPropertyName(), lastGroup);
            break;
        } else {
            if (lastGroup == null)
                continue;
            int j = lastGroup.indexOf('?');
            if (j > -1) {
                lastGroup = lastGroup.substring(0, j);
            }
            if (constraints.length > i) {
                ConstrainedProperty cp = constraints[i];
                cp.validate(this, lastGroup, errors);

                if (errors.hasErrors()) {
                    return null;
                }

                params.put(cp.getPropertyName(), lastGroup);
            }
        }

    }

    for (Object key : parameterValues.keySet()) {
        params.put(key, parameterValues.get(key));
    }

    if (controllerName == null) {
        controllerName = createRuntimeConstraintEvaluator(GrailsControllerClass.CONTROLLER, constraints);
    }

    if (actionName == null) {
        actionName = createRuntimeConstraintEvaluator(GrailsControllerClass.ACTION, constraints);
    }

    if (namespace == null) {
        namespace = createRuntimeConstraintEvaluator(NAMESPACE, constraints);
    }

    if (viewName == null) {
        viewName = createRuntimeConstraintEvaluator(GrailsControllerClass.VIEW, constraints);
    }

    if (redirectInfo == null) {
        redirectInfo = createRuntimeConstraintEvaluator("redirect", constraints);
    }

    DefaultUrlMappingInfo info;
    if (forwardURI != null && controllerName == null) {
        info = new DefaultUrlMappingInfo(forwardURI, getHttpMethod(), urlData, servletContext);
    } else if (viewName != null && controllerName == null) {
        info = new DefaultUrlMappingInfo(viewName, params, urlData, servletContext);
    } else {
        info = new DefaultUrlMappingInfo(redirectInfo, controllerName, actionName, namespace, pluginName,
                getViewName(), getHttpMethod(), getVersion(), params, urlData, servletContext);
    }

    if (parseRequest) {
        info.setParsingRequest(parseRequest);
    }

    return info;
}

From source file:com.ephesoft.dcma.tablefinder.share.TableRowFinderUtility.java

/**
 * Method is responsible for finding the patterns and returned the found data List.
 * /*from   www . ja  v  a 2  s  . com*/
 * @param value
 * @param patternStr
 * @param spanList
 * @return
 * @throws DCMAApplicationException {@link DCMAApplicationException} Check for all the input parameters and find the pattern.
 */
public static final List<DataCarrier> findPattern(final String value, final String patternStr,
        final List<Span> spanList) throws DCMAApplicationException {

    String errMsg = null;
    List<DataCarrier> dataCarrierList = null;
    if (EphesoftStringUtil.isNullOrEmpty(value)) {
        errMsg = "Invalid input character sequence.";
        LOGGER.info(errMsg);
    } else if (null == patternStr || TableExtractionConstants.EMPTY.equals(patternStr)) {
        errMsg = "Invalid input pattern sequence.";
        throw new DCMAApplicationException(errMsg);
    } else {
        // Compile and use regular expression
        final CharSequence inputStr = value;
        final Pattern pattern = Pattern.compile(patternStr);
        final Matcher matcher = pattern.matcher(inputStr);
        List<Coordinates> coordinatesList = new ArrayList<Coordinates>();
        while (matcher.find()) {

            // Get all groups for this match
            for (int i = 0; i <= matcher.groupCount(); i++) {
                final String groupStr = matcher.group(i);
                if (groupStr != null) {
                    final int startIndex = matcher.start();
                    final int endIndex = startIndex + groupStr.trim().length();
                    List<Span> matchedSpans = null;
                    matchedSpans = PatternMatcherUtil.getMatchedSpans(spanList, startIndex, endIndex);
                    String matchedString = PatternMatcherUtil.getMatchedSpansValue(matchedSpans);
                    LOGGER.debug("Matched String is ", matchedString);
                    if (!EphesoftStringUtil.isNullOrEmpty(matchedString)) {
                        final float confidence = (groupStr.length()
                                * CommonConstants.DEFAULT_MAXIMUM_CONFIDENCE) / matchedString.length();
                        coordinatesList.clear();
                        for (Span span : matchedSpans) {
                            coordinatesList.add(span.getCoordinates());
                        }
                        Coordinates matchedCoordinates = HocrUtil.getRectangleCoordinates(coordinatesList);
                        final DataCarrier dataCarrier = new DataCarrier(matchedSpans, confidence, matchedString,
                                matchedCoordinates);
                        if (dataCarrierList == null) {
                            dataCarrierList = new ArrayList<DataCarrier>();
                        }
                        dataCarrierList.add(dataCarrier);
                        LOGGER.info(groupStr);
                    }
                }
            }
        }
    }

    return dataCarrierList;
}