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.andrewberman.sync.InheritMe.java

static LinkedHashMap<String, ArrayList<String>> getTagsFromPage(String pageURL, String pageContent)
        throws Exception {
    LinkedHashMap<String, ArrayList<String>> idToURL = new LinkedHashMap<String, ArrayList<String>>();
    Matcher m = chunkGrabber.matcher(pageContent);
    while (m.find()) {
        /*// w ww  .ja va  2 s .c  o m
         * Chunk contains the article URL, and everything up until the next <li> element.
         */
        String chunk = m.group();
        /*
         * First, extract the article ID.
         */
        Matcher m2 = articleURL.matcher(chunk);
        m2.find();
        String aid = m2.group(m2.groupCount());

        /*
         * Now we want to send the chunk through tagFinder and get the tags.
         */
        ArrayList<String> tags = new ArrayList<String>();
        Matcher m3 = tagFinder.matcher(chunk);
        while (m3.find()) {
            String tag = m3.group(m3.groupCount());
            tags.add(tag);
        }
        idToURL.put(aid, tags);
    }
    return idToURL;
}

From source file:org.eclipse.virgo.kernel.osgi.provisioning.tools.DependencyLocator10.java

private static String expandProperties(String value) {
    Pattern regex = PROPERTY_PATTERN;
    StringBuffer buffer = new StringBuffer(value.length());
    Matcher matcher = regex.matcher(value);
    int propertyGroup = matcher.groupCount();
    String key, property = "";
    while (matcher.find()) {
        key = matcher.group(propertyGroup);
        property = "";
        if (key.contains("::")) {
            String[] keyDefault = key.split("::");
            property = System.getProperty(keyDefault[0]);
            if (property == null) {
                property = keyDefault[1];
            } else {
                property = property.replace('\\', '/');
            }/* w  ww  . j  av a  2 s  . com*/
        } else {
            property = System.getProperty(matcher.group(propertyGroup)).replace('\\', '/');
        }
        matcher.appendReplacement(buffer, property);
    }
    matcher.appendTail(buffer);
    return buffer.toString();
}

From source file:architecture.common.util.StringUtils.java

public static boolean isValidEmailAddress(String addr) {
    if (addr == null)
        return false;
    addr = addr.trim();/*from w  w w . ja  v  a  2s  . c  o  m*/
    if (addr.length() == 0)
        return false;
    Matcher matcher = basicAddressPattern.matcher(addr);
    if (!matcher.matches())
        return false;
    String userPart = matcher.group(1);
    String domainPart = matcher.group(2);
    matcher = validUserPattern.matcher(userPart);
    if (!matcher.matches())
        return false;
    matcher = ipDomainPattern.matcher(domainPart);
    if (matcher.matches()) {
        for (int i = 1; i < 5; i++) {
            String num = matcher.group(i);
            if (num == null)
                return false;
            if (Integer.parseInt(num) > 254)
                return false;
        }

        return true;
    }
    matcher = domainPattern.matcher(domainPart);
    if (matcher.matches()) {
        String tld = matcher.group(matcher.groupCount());
        matcher = tldPattern.matcher(tld);
        return tld.length() == 3 || matcher.matches();
    } else {
        return "localhost".equals(domainPart);
    }
}

From source file:gedi.util.FileUtils.java

public static String findPartnerFile(String path, String regex) throws IOException {
    if (path.contains(" "))
        return EI.split(path, ' ').map(f -> {
            try {
                return findPartnerFile(f, regex);
            } catch (IOException e) {
                throw new RuntimeException("Could not find partner file", e);
            }/* www  .  j  a va  2  s .  com*/
        }).concat(" ");

    Pattern p = Pattern.compile(regex);
    String name = new File(path).getName();
    Matcher pm = p.matcher(name);
    if (!pm.find())
        throw new IllegalArgumentException(
                "Given path does not match the regular expression: " + name + " " + regex);

    String pk = EI.seq(1, 1 + pm.groupCount()).map(g -> pm.group(g)).concat();

    String folder = new File(path).getAbsoluteFile().getParent();
    String rename = EI.files(folder).map(f -> f.getName()).filter(s -> !s.equals(name)).filter(s -> {
        Matcher sm = p.matcher(s);
        if (!sm.find())
            return false;
        String sk = EI.seq(1, 1 + sm.groupCount()).map(g -> sm.group(g)).concat();
        return sk.equals(pk);
    }).getUniqueResult("More than one matching file found (" + path + ")!",
            "No matching file found (" + path + ")!");

    return new File(new File(path).getParent(), rename).getPath();
}

From source file:com.jsystem.j2autoit.AutoItAgent.java

private static String extractLocation(String regkey) throws Exception {
    String cmd = "reg query " + regkey + " /ve";
    Process child = Runtime.getRuntime().exec(cmd);
    child.waitFor();// w  w  w .  j  a va  2  s .c o m
    BufferedReader br = new BufferedReader(new InputStreamReader(child.getInputStream()));
    StringBuffer sb = new StringBuffer("");
    String line = null;
    while ((line = br.readLine()) != null) {
        sb.append(line).append(NEW_LINE);
    }
    Matcher mat = PATTERN_EXTRACTING_AUTOIT_LOCATION.matcher(sb.toString());
    if (mat.find()) {
        return mat.group(mat.groupCount()).trim();
    } else {
        throw new Exception("Unable to find AutoIt Location");
    }
}

From source file:gal.udc.fic.muei.tfm.dap.flipper.config.cassandra.CassandraProperties.java

/**
 * Get the reconnection policy.//  w ww  .ja  va  2 s . c  o  m
 */
public static ReconnectionPolicy getReconnectionPolicy(String rcString, String parameters)
        throws ClassNotFoundException, NoSuchMethodException, SecurityException, InstantiationException,
        IllegalAccessException, IllegalArgumentException, InvocationTargetException {
    ReconnectionPolicy policy = null;
    //ReconnectionPolicy childPolicy = null;
    if (!rcString.contains(".")) {
        rcString = "com.datastax.driver.core.policies." + rcString;
    }

    if (parameters.length() > 0) {
        // Child policy or parameters have been specified
        String paramsRegex = "([^,]+\\(.+?\\))|([^,]+)";
        Pattern param_pattern = Pattern.compile(paramsRegex);
        Matcher lb_matcher = param_pattern.matcher(parameters);

        ArrayList<Object> paramList = Lists.newArrayList();
        ArrayList<Class> primaryParametersClasses = Lists.newArrayList();
        int nb = 0;
        while (lb_matcher.find()) {
            if (lb_matcher.groupCount() > 0) {
                try {
                    if (lb_matcher.group().contains("(") && !lb_matcher.group().trim().startsWith("(")) {
                        // We are dealing with child policies here
                        primaryParametersClasses.add(LoadBalancingPolicy.class);
                        // Parse and add child policy to the parameter list
                        paramList.add(parseReconnectionPolicy(lb_matcher.group()));
                        nb++;
                    } else {
                        // We are dealing with parameters that are not policies here
                        String param = lb_matcher.group();
                        if (param.contains("'") || param.contains("\"")) {
                            primaryParametersClasses.add(String.class);
                            paramList.add(new String(param.trim().replace("'", "").replace("\"", "")));
                        } else if (param.contains(".") || param.toLowerCase().contains("(double)")
                                || param.toLowerCase().contains("(float)")) {
                            // gotta allow using float or double
                            if (param.toLowerCase().contains("(double)")) {
                                primaryParametersClasses.add(double.class);
                                paramList.add(Double.parseDouble(param.replace("(double)", "").trim()));
                            } else {
                                primaryParametersClasses.add(float.class);
                                paramList.add(Float.parseFloat(param.replace("(float)", "").trim()));
                            }
                        } else {
                            if (param.toLowerCase().contains("(long)")) {
                                primaryParametersClasses.add(long.class);
                                paramList.add(Long.parseLong(param.toLowerCase().replace("(long)", "").trim()));
                            } else {
                                primaryParametersClasses.add(int.class);
                                paramList
                                        .add(Integer.parseInt(param.toLowerCase().replace("(int)", "").trim()));
                            }
                        }
                        nb++;
                    }
                } catch (Exception e) {
                    log.error("Could not parse the Cassandra reconnection policy! " + e.getMessage());
                }
            }
        }

        if (nb > 0) {
            // Instantiate load balancing policy with parameters
            Class<?> clazz = Class.forName(rcString);
            Constructor<?> constructor = clazz.getConstructor(
                    primaryParametersClasses.toArray(new Class[primaryParametersClasses.size()]));

            return (ReconnectionPolicy) constructor
                    .newInstance(paramList.toArray(new Object[paramList.size()]));
        }
        // Only one policy has been specified, with no parameter or child policy
        Class<?> clazz = Class.forName(rcString);
        policy = (ReconnectionPolicy) clazz.newInstance();
        return policy;
    }
    Class<?> clazz = Class.forName(rcString);
    policy = (ReconnectionPolicy) clazz.newInstance();
    return policy;
}

From source file:com.example.app.support.address.AddressParser.java

private static Map<AddressComponent, String> getAddrMap(Matcher m, Map<Integer, String> groupMap) {
    Map<AddressComponent, String> ret = new EnumMap<>(AddressComponent.class);
    for (int i = 1; i <= m.groupCount(); i++) {
        String name = groupMap.get(i);
        AddressComponent comp = valueOf(name);
        if (ret.get(comp) == null) {
            putIfNotNull(ret, comp, m.group(i));
        }//from w  ww.j  a v a 2s  .  c  om
    }
    return ret;
}

From source file:gal.udc.fic.muei.tfm.dap.flipper.config.cassandra.CassandraProperties.java

/**
 * Get the load balancing policy./*from   w w  w.ja v  a 2  s  .c o m*/
 */
public static LoadBalancingPolicy getLbPolicy(String lbString, String parameters)
        throws ClassNotFoundException, NoSuchMethodException, SecurityException, InstantiationException,
        IllegalAccessException, IllegalArgumentException, InvocationTargetException {
    LoadBalancingPolicy policy = null;
    if (!lbString.contains(".")) {
        lbString = "com.datastax.driver.core.policies." + lbString;
    }

    if (parameters.length() > 0) {
        // Child policy or parameters have been specified
        String paramsRegex = "([^,]+\\(.+?\\))|([^,]+)";
        Pattern param_pattern = Pattern.compile(paramsRegex);
        Matcher lb_matcher = param_pattern.matcher(parameters);

        ArrayList<Object> paramList = Lists.newArrayList();
        ArrayList<Class> primaryParametersClasses = Lists.newArrayList();
        int nb = 0;
        while (lb_matcher.find()) {
            if (lb_matcher.groupCount() > 0) {
                try {
                    if (lb_matcher.group().contains("(") && !lb_matcher.group().trim().startsWith("(")) {
                        // We are dealing with child policies here
                        primaryParametersClasses.add(LoadBalancingPolicy.class);
                        // Parse and add child policy to the parameter list
                        paramList.add(parseLbPolicy(lb_matcher.group()));
                        nb++;
                    } else {
                        // We are dealing with parameters that are not policies here
                        String param = lb_matcher.group();
                        if (param.contains("'") || param.contains("\"")) {
                            primaryParametersClasses.add(String.class);
                            paramList.add(new String(param.trim().replace("'", "").replace("\"", "")));
                        } else if (param.contains(".") || param.toLowerCase().contains("(double)")
                                || param.toLowerCase().contains("(float)")) {
                            // gotta allow using float or double
                            if (param.toLowerCase().contains("(double)")) {
                                primaryParametersClasses.add(double.class);
                                paramList.add(Double.parseDouble(param.replace("(double)", "").trim()));
                            } else {
                                primaryParametersClasses.add(float.class);
                                paramList.add(Float.parseFloat(param.replace("(float)", "").trim()));
                            }
                        } else {
                            if (param.toLowerCase().contains("(long)")) {
                                primaryParametersClasses.add(long.class);
                                paramList.add(Long.parseLong(param.toLowerCase().replace("(long)", "").trim()));
                            } else {
                                primaryParametersClasses.add(int.class);
                                paramList
                                        .add(Integer.parseInt(param.toLowerCase().replace("(int)", "").trim()));
                            }
                        }
                        nb++;
                    }
                } catch (Exception e) {
                    log.error("Could not parse the Cassandra load balancing policy! " + e.getMessage());
                }
            }
        }
        if (nb > 0) {
            // Instantiate load balancing policy with parameters
            if (lbString.toLowerCase().contains("latencyawarepolicy")) {
                //special sauce for the latency aware policy which uses a builder subclass to instantiate
                Builder builder = LatencyAwarePolicy.builder((LoadBalancingPolicy) paramList.get(0));

                builder.withExclusionThreshold((Double) paramList.get(1));
                builder.withScale((Long) paramList.get(2), TimeUnit.MILLISECONDS);
                builder.withRetryPeriod((Long) paramList.get(3), TimeUnit.MILLISECONDS);
                builder.withUpdateRate((Long) paramList.get(4), TimeUnit.MILLISECONDS);
                builder.withMininumMeasurements((Integer) paramList.get(5));

                return builder.build();

            } else {
                Class<?> clazz = Class.forName(lbString);
                Constructor<?> constructor = clazz.getConstructor(
                        primaryParametersClasses.toArray(new Class[primaryParametersClasses.size()]));

                return (LoadBalancingPolicy) constructor
                        .newInstance(paramList.toArray(new Object[paramList.size()]));
            }
        } else {
            // Only one policy has been specified, with no parameter or child policy
            Class<?> clazz = Class.forName(lbString);
            policy = (LoadBalancingPolicy) clazz.newInstance();
            return policy;
        }
    } else {
        // Only one policy has been specified, with no parameter or child policy
        Class<?> clazz = Class.forName(lbString);
        policy = (LoadBalancingPolicy) clazz.newInstance();
        return policy;
    }
}

From source file:info.icefilms.icestream.browse.Location.java

protected static String GetGroup(String[] regex, int flags, String source) {
    // Combine all the regular expressions
    String expression = "(" + regex[0] + ")";
    for (int i = 1; i < regex.length; ++i)
        expression += "|(" + regex[i] + ")";

    // Define the matcher
    Matcher matcher;
    if (flags == -1)
        matcher = Pattern.compile(expression).matcher(source);
    else//from  w  ww.  j av  a  2s .c o  m
        matcher = Pattern.compile(expression, flags).matcher(source);

    // Check if we found anything
    if (matcher.find() == false) {
        return null;
    } else {
        // Return the group we found
        for (int i = 2; i <= matcher.groupCount(); i += 2)
            if (matcher.group(i) != null)
                return matcher.group(i);

        return null;
    }
}

From source file:org.mzd.shap.spring.io.DescriptionEditor.java

public String getMinimalDescription(String fullDescription) {
    Matcher m = getPattern().matcher(fullDescription);

    if (m.groupCount() <= 0 || !m.matches()) {
        return fullDescription;
    }/* w  ww  .  j  av a2 s. co m*/

    return m.group(1);
}