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:org.auscope.portal.server.gridjob.ScriptParser.java

private int extractInt(final String regex) {
    Pattern p = Pattern.compile(regex);
    Matcher m = p.matcher(scriptText);
    int result = 0;
    if (m.find() && m.groupCount() >= 1) {
        try {/*from   w  w  w. ja  va  2  s. co  m*/
            result = Integer.parseInt(m.group(1));
        } catch (NumberFormatException e) {
            logger.warn("Exception while parsing int: " + e.getMessage());
        }
    } else {
        logger.warn("No match for '" + regex + "'!");
    }
    return result;
}

From source file:io.wcm.tooling.netbeans.sightly.completion.classLookup.MemberLookupCompleter.java

/**
 * This method tries to find the class which is defined for the given filter and returns a set with all methods and fields of the class
 *
 * @param variableName// www. j  a  v a 2  s . co m
 * @param text
 * @param document
 * @return Set of methods and fields, never null
 */
private Set<String> resolveClass(String variableName, String text, Document document) {
    Set<String> items = new LinkedHashSet<>();
    FileObject fo = getFileObject(document);
    ClassPath sourcePath = ClassPath.getClassPath(fo, ClassPath.SOURCE);
    ClassPath compilePath = ClassPath.getClassPath(fo, ClassPath.COMPILE);
    ClassPath bootPath = ClassPath.getClassPath(fo, ClassPath.BOOT);
    if (sourcePath == null) {
        return items;
    }
    ClassPath cp = ClassPathSupport.createProxyClassPath(sourcePath, compilePath, bootPath);
    MemberLookupResolver resolver = new MemberLookupResolver(text, cp);
    Set<MemberLookupResult> results = resolver.performMemberLookup(
            StringUtils.defaultString(StringUtils.substringBeforeLast(variableName, "."), variableName));
    for (MemberLookupResult result : results) {
        Matcher m = GETTER_PATTERN.matcher(result.getMethodName());
        if (m.matches() && m.groupCount() >= 2) {
            items.add(result.getVariableName() + "." + WordUtils.uncapitalize(m.group(2)));
        } else {
            items.add(result.getVariableName() + "." + WordUtils.uncapitalize(result.getMethodName()));
        }
    }
    return items;
}

From source file:org.cleverbus.admin.services.log.LogParser.java

/**
 * Parses a log line into a new LogEvent,
 * verifying fields against required values specified by {@link LogParserConfig#getFilter()}.
 *
 * @param matcher the matcher generated based on {@link LogParserConfig#getPropertiesPattern()}
 * @return true if log event properties were parsed from the matcher; false otherwise
 *///from   w  ww  .  java 2s  . c  om
private boolean parseEventProperties(Matcher matcher, LogEvent logEvent, LogParserConfig config) {
    assert matcher.groupCount() >= config.getPropertyCount();
    for (int propertyIndex = 0; propertyIndex < logEvent.getPropertyCount(); propertyIndex++) {
        String propertyValue = matcher.group(propertyIndex + 1);
        if (!config.isMatchesFilter(propertyValue, propertyIndex)) {
            return false;
        }
        logEvent.getProperties()[propertyIndex] = propertyValue;
    }
    return true;
}

From source file:org.esco.portlet.flashinfo.service.bean.FlashUrlBuilderImpl.java

@Override
public String transform(final PortletRequest request, final String url) {
    String rewroteUrl = url;/*from  ww  w .  j  a  va  2  s  . com*/
    if (log.isDebugEnabled()) {
        log.debug("Url in entry is '{}'", rewroteUrl);
    }
    final Matcher matcher = p.matcher(url);
    if (matcher.find()) {
        for (int i = 1; i <= matcher.groupCount(); i++) {
            // Using the first value only
            final List<String> values = userResource.getUserInfo(request, matcher.group(i));
            if (values != null && !values.isEmpty()) {
                rewroteUrl = rewroteUrl.replaceAll("\\{" + matcher.group(i) + "\\}", values.get(0));
            } else {
                log.warn("No value was retrived from user info of '{}' on attribute '{}'",
                        request.getUserPrincipal(), matcher.group(i));
            }
        }
    }
    if (log.isDebugEnabled()) {
        log.debug("Replacement regexp of flashUrl from {} to {}", url, rewroteUrl);
    }

    try {
        final URI uri = new URI(rewroteUrl);
        if (uri.getScheme() == null && uri.getHost() == null) {
            final int tmpPort = request.getServerPort();
            final String port = ((tmpPort != 80) && (tmpPort != 443) && (tmpPort > 0)) ? ":" + tmpPort : "";
            // if start with // we add only the scheme
            // else if relative url start with / we add to the url only the scheme and domain
            // else if relative url we add sheme + domain + contextPath so in this case only we need to context path
            final String ctx = (!rewroteUrl.startsWith("//") && !rewroteUrl.startsWith("/"))
                    ? request.getContextPath() + "/"
                    : "";
            if (log.isDebugEnabled()) {
                log.debug(
                        "Rewrite flashUrl from {} to {}, with params scheme {}, host {}, port {}, context path {}",
                        rewroteUrl,
                        request.getScheme() + "://" + request.getServerName() + port + ctx + rewroteUrl,
                        request.getScheme(), request.getServerName(), port, ctx);
            }
            rewroteUrl = request.getScheme() + "://" + request.getServerName() + port + ctx + rewroteUrl;
        } else if (uri.getScheme() == null) {
            final String path = !rewroteUrl.startsWith("//") ? "//" : "";
            if (log.isDebugEnabled()) {
                log.debug("Rewrite flashUrl from {} to {}, with params scheme {}", rewroteUrl,
                        request.getScheme() + ":" + path + rewroteUrl, request.getScheme() + path);
            }
            rewroteUrl = request.getScheme() + ":" + path + rewroteUrl;
        }
    } catch (URISyntaxException e) {
        log.error("The url '" + rewroteUrl + "' to get flashInfos is malformed !", e);
        return null;
    }
    if (log.isDebugEnabled()) {
        log.debug("Url at end is '{}'", rewroteUrl);
    }
    return rewroteUrl;
}

From source file:org.auscope.portal.server.gridjob.ScriptParser.java

private float extractFloat(final String regex) {
    Pattern p = Pattern.compile(regex);
    Matcher m = p.matcher(scriptText);
    float result = 0.0f;
    if (m.find() && m.groupCount() >= 1) {
        try {/*from   w ww.  j a  v a 2 s  .  c  om*/
            result = Float.parseFloat(m.group(1));
        } catch (NumberFormatException e) {
            logger.warn("Exception while parsing float: " + e.getMessage());
        }
    } else {
        logger.warn("No match for '" + regex + "'!");
    }
    return result;
}

From source file:com.liferay.ide.project.core.upgrade.UpgradeMetadataHandler.java

private String getNewDoctTypeSetting(String doctypeSetting, String newValue, String regrex) {
    String newDoctTypeSetting = null;
    Pattern p = Pattern.compile(regrex, Pattern.CASE_INSENSITIVE | Pattern.DOTALL);
    Matcher m = p.matcher(doctypeSetting);

    if (m.find()) {
        String oldVersionString = m.group(m.groupCount());
        newDoctTypeSetting = doctypeSetting.replace(oldVersionString, newValue);
    }//  ww w  . j  a v a  2s . c  o m

    return newDoctTypeSetting;
}

From source file:org.candlepin.exceptions.mappers.BadRequestExceptionMapper.java

private String extractIllegalValue(String msg) {
    Matcher paramMatcher = PARAM_REGEX.matcher(msg);
    Matcher illegalValMatcher = ILLEGAL_VAL_REGEX.matcher(msg);
    if (paramMatcher.find() && illegalValMatcher.find()) {
        if ((paramMatcher.groupCount() & illegalValMatcher.groupCount()) == 2) {
            return i18n.tr("{0} is not a valid value for {1}", illegalValMatcher.group(1),
                    paramMatcher.group(1));
        }/* ww w  .  j a  va 2  s  .  c o m*/
    }
    return i18n.tr("Bad Request");
}

From source file:$.LogParser.java

/**
     * Parses a log line into a new LogEvent,
     * verifying fields against required values specified by {@link LogParserConfig${symbol_pound}getFilter()}.
     */*w w w.ja v  a2 s. com*/
     * @param matcher the matcher generated based on {@link LogParserConfig${symbol_pound}getPropertiesPattern()}
     * @return true if log event properties were parsed from the matcher; false otherwise
     */
    private boolean parseEventProperties(Matcher matcher, LogEvent logEvent, LogParserConfig config) {
        assert matcher.groupCount() >= config.getPropertyCount();
        for (int propertyIndex = 0; propertyIndex < logEvent.getPropertyCount(); propertyIndex++) {
            String propertyValue = matcher.group(propertyIndex + 1);
            if (!config.isMatchesFilter(propertyValue, propertyIndex)) {
                return false;
            }
            logEvent.getProperties()[propertyIndex] = propertyValue;
        }
        return true;
    }

From source file:nz.net.orcon.kanban.automation.actions.RegexAction.java

public String extract(String text, String expressionString, int match, int group, String options)
        throws IOException {

    if (text == null) {
        text = "";
    }/*from   www .  j  ava 2 s.c o  m*/

    if (expressionString == null) {
        throw new IllegalArgumentException(
                "No Regular Expression has been provided to carry out this operation.");
    }

    int optionsInEffect = 0;
    if (options != null) {
        for (String option : options.toUpperCase().split("\\|")) {
            optionsInEffect |= (option.equals("CANON_EQ")) ? Pattern.CANON_EQ
                    : (option.equals("CASE_INSENSITIVE")) ? Pattern.CASE_INSENSITIVE
                            : (option.equals("COMMENTS")) ? Pattern.COMMENTS
                                    : (option.equals("DOTALL")) ? Pattern.DOTALL
                                            : (option.equals("LITERAL")) ? Pattern.LITERAL
                                                    : (option.equals("MULTILINE")) ? Pattern.MULTILINE
                                                            : (option.equals("UNICODE_CASE"))
                                                                    ? Pattern.UNICODE_CASE
                                                                    : (option.equals("UNIX_LINES"))
                                                                            ? Pattern.UNIX_LINES
                                                                            : 0;
        }
    }

    Pattern expression = Pattern.compile(expressionString, optionsInEffect);
    Matcher matches = expression.matcher(text);

    int matchIndex = 1;
    while (matches.find()) {
        for (int groupIndex = 0; matches.groupCount() + 1 > groupIndex; groupIndex++) {
            if (matchIndex == match && groupIndex == group) {
                return matches.group(groupIndex);
            }
        }
        matchIndex++;
    }

    return "";
}

From source file:se.crisp.codekvast.agent.daemon.appversion.FilenameAppVersionStrategy.java

private String search(File dir, Pattern pattern) {
    if (!dir.isDirectory()) {
        log.warn("{} is not a directory", dir);
        return null;
    }//w w  w . j av  a  2s  .co m

    File[] files = dir.listFiles();

    if (files != null) {
        for (File file : files) {
            if (file.isFile()) {
                Matcher matcher = pattern.matcher(file.getName());
                if (matcher.matches()) {
                    String version = matcher.group(matcher.groupCount());
                    log.debug("Found version '{}' in {}", version, file);
                    return version;
                }
            }
        }
        for (File file : files) {
            if (file.isDirectory()) {
                String version = search(file, pattern);
                if (version != null) {
                    return version;
                }
            }
        }
    }
    return null;
}