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:at.alladin.rmbt.qos.testscript.TestScriptInterpreter.java

/**
 * //  www. jav a 2s  . co m
 * @param command
 * @return
 */
public static <T> Object interprete(String command, Hstore hstore, AbstractResult<T> object,
        boolean useRecursion, ResultOptions resultOptions) {

    if (jsEngine == null) {
        ScriptEngineManager sem = new ScriptEngineManager();
        jsEngine = sem.getEngineByName("JavaScript");
        System.out.println("JS Engine: " + jsEngine.getClass().getCanonicalName());
        Bindings b = jsEngine.createBindings();
        b.put("nn", new SystemApi());
        jsEngine.setBindings(b, ScriptContext.GLOBAL_SCOPE);
    }

    command = command.replace("\\%", "{PERCENT}");

    Pattern p;
    if (!useRecursion) {
        p = PATTERN_COMMAND;
    } else {
        p = PATTERN_RECURSIVE_COMMAND;

        Matcher m = p.matcher(command);
        while (m.find()) {
            String replace = m.group(0);
            //System.out.println("found: " + replace);
            String toReplace = String.valueOf(interprete(replace, hstore, object, false, resultOptions));
            //System.out.println("replacing: " + m.group(0) + " -> " + toReplace);
            command = command.replace(m.group(0), toReplace);
        }

        command = command.replace("{PERCENT}", "%");
        return command;
    }

    Matcher m = p.matcher(command);
    command = command.replace("{PERCENT}", "%");

    String scriptCommand;
    String[] args;

    if (m.find()) {
        if (m.groupCount() != 2) {
            return command;
        }
        scriptCommand = m.group(1);

        if (!COMMAND_EVAL.equals(scriptCommand)) {
            args = m.group(2).trim().split("\\s");
        } else {
            args = new String[] { m.group(2).trim() };
        }
    } else {
        return command;
    }

    try {
        if (COMMAND_RANDOM.equals(scriptCommand)) {
            return random(args);
        } else if (COMMAND_PARAM.equals(scriptCommand)) {
            return parse(args, hstore, object, resultOptions);
        } else if (COMMAND_EVAL.equals(scriptCommand)) {
            return eval(args, hstore, object);
        } else if (COMMAND_RANDOM_URL.equals(scriptCommand)) {
            return randomUrl(args);
        } else {
            return command;
        }
    } catch (ScriptException e) {
        e.printStackTrace();
        return null;
    }
}

From source file:com.tacitknowledge.util.migration.jdbc.loader.FlatXmlDataSetTaskSource.java

/**
 * Creates a list of {@link FlatXmlDataSetMigrationTask}s based on the array
 * of xml files./*from   w ww.  ja v  a2 s  .c  o  m*/
 *
 * @param xmlFiles the classpath-relative array of xml files
 * @return a list of {@link FlatXmlDataSetMigrationTask}
 * @throws MigrationException in unexpected error occurs
 */
private List<MigrationTask> createMigrationTasks(String[] xmlFiles) throws MigrationException {
    Pattern p = Pattern.compile(XML_PATCH_REGEX);
    List<MigrationTask> tasks = new ArrayList<MigrationTask>();
    for (int i = 0; i < xmlFiles.length; i++) {
        String xmlPathname = xmlFiles[i];
        xmlPathname = xmlPathname.replace('\\', '/');
        log.debug("Examining possible xml patch file \"" + xmlPathname + "\"");

        File xmlFile = new File(xmlPathname);
        String xmlFilename = xmlFile.getName();

        // Get the patch number out of the file name
        Matcher matcher = p.matcher(xmlFilename);
        if (!matcher.matches() || matcher.groupCount() != 2) {
            throw new MigrationException("Invalid XML patch name: " + xmlFilename);
        }

        FlatXmlDataSetMigrationTask task = new FlatXmlDataSetMigrationTask();
        task.setLevel(new Integer(Integer.parseInt(matcher.group(1))));
        task.setName(xmlPathname);
        tasks.add(task);

    }
    return tasks;
}

From source file:com.android.example.github.api.ApiResponse.java

public Integer getNextPage() {
    String next = links.get(NEXT_LINK);
    if (next == null) {
        return null;
    }//from  w w  w . ja v a 2  s  . c  om
    Matcher matcher = PAGE_PATTERN.matcher(next);
    if (!matcher.find() || matcher.groupCount() != 1) {
        return null;
    }
    try {
        return Integer.parseInt(matcher.group(1));
    } catch (NumberFormatException ex) {
        Timber.w("cannot parse next page from %s", next);
        return null;
    }
}

From source file:org.codehaus.mojo.license.osgi.AboutFileLicenseResolver.java

private List<String> findGroupOccurrences(String content, Pattern pattern, int groupNumber) {
    List<String> matches = new ArrayList<String>();
    Matcher matcher = pattern.matcher(content);
    while (matcher.find()) {
        if (groupNumber <= matcher.groupCount()) {
            matches.add(matcher.group(groupNumber));
        }//from  ww w.  j a  va2  s  .c  om
    }
    return matches;
}

From source file:org.apache.struts.maven.snippetextractor.parser.SnippetParser.java

private boolean doesContainSnippetEnd(Matcher matcher) {
    return matcher.find() && matcher.groupCount() == 3;
}

From source file:com.swordlord.jalapeno.datacontainer.DataContainer.java

/**
 * Filters the given rows using an complex filter.
 * //  w  ww.j a v  a2 s .  com
 * @param <T>
 *            The row type
 * @param rows
 *            The rows to process
 * @param filter
 *            The complex filter
 * @param context
 *            The binding context or null
 * @param dt
 *            The table to which the rows belong
 * @return The filtered rows
 */
private static <T> List<T> complexFilter(List<T> rows, DataBindingContext context, DataTableBase dt,
        String filter) {
    // Example of a filter: ?NotIn(threatId,@ActiveThreat[0]:threatId)
    final Pattern pattern = Pattern.compile(
            "^(\\?)?([a-z]*)(\\(){1,1}([a-z]*)?(,){1,1}([(\\?)?a-z_0-9,:='%\\s@\\[\\]\\(\\)]*)?(\\)){1,1}$",
            Pattern.CASE_INSENSITIVE | Pattern.MULTILINE);
    final Matcher matcher = pattern.matcher(filter);

    /*
     * The groups are as follows 1 - ! 2 - NotIn 3 - ( 4 - threatId 5 -
     * , 6 - @ActiveThreat[0]:threatId 7 - )
     */

    if (!matcher.find()) {
        LOG.info("Parser can't parse filter: " + filter);
        return rows;
    }

    if (matcher.groupCount() != 7) {
        LOG.error("Wrong group count during parsing of filter: " + filter);
        return rows;
    }

    final String strCommand = matcher.group(2);
    final String strBoundField = matcher.group(4).replace(":", ".");
    final String strBindingMember = matcher.group(6).replace(":", ".");

    final DataBindingMember bm = new DataBindingMember(strBindingMember);

    // re-use the DataBindingContext when there is one
    // this is needed so that all currentRow informations are correct
    // within a filter
    final DataBindingManager dbm;
    if (context != null) {
        dbm = context.getDataBindingManager(bm);
    } else {
        dbm = new DataBindingManager(dt.getDataContainer(), bm);
    }

    // get all to-be-filtered records as field because the expression
    // filters on one single field and does no lookup
    final List<String> fieldsFilter = new ArrayList<String>();
    for (DataRowBase row : dbm.getRows(bm)) {
        if (row.getPersistenceState() != PersistenceState.DELETED) {
            final String strFieldName = bm.getDataBindingFieldName();
            if (strFieldName == null || strFieldName.length() == 0) {
                LOG.error("There must be something wrong with your filter. Field is empty: " + filter);
            } else {
                fieldsFilter.add(row.getPropertyAsStringForce(strFieldName));
            }
        }
    }

    // Create the expression according to the binding information
    if (strCommand.equalsIgnoreCase("in")) {
        final Expression exp = ExpressionFactory.inExp(strBoundField, fieldsFilter);
        return new ArrayList<T>(exp.filterObjects(rows));
    } else if (strCommand.equalsIgnoreCase("notin")) {
        final Expression exp = ExpressionFactory.notInExp(strBoundField, fieldsFilter);
        return new ArrayList<T>(exp.filterObjects(rows));
    } else {
        LOG.warn("Unknown filter command: " + strCommand);
        return rows;
    }
}

From source file:org.acmsl.commons.regexpplugin.jdk14regexp.MatchResultJDKAdapter.java

/**
 * Taken from JDK 1.4 javadoc:/*from  w  w w  .  ja  v a 2  s . co  m*/
 * @param matcher the matcher.
 * <i>Returns the number of capturing groups in this matcher's
 * pattern.</i>.
 * @return such value.
 */
protected int groups(final Matcher matcher) {
    return matcher.groupCount();
}

From source file:org.diorite.config.impl.actions.AbstractPropertyAction.java

@Override
public ActionMatcherResult matchesAction(Method method) {
    MethodInvoker methodInvoker = new MethodInvoker(method);
    if (methodInvoker.isStatic() || methodInvoker.isNative()) {
        return FAIL;
    }//w  ww  . j  av  a2s  .  c o m
    for (Pattern pattern : this.patterns) {
        Matcher matcher = pattern.matcher(method.getName());
        if (matcher.matches() && (matcher.groupCount() > 0)) {
            String property = matcher.group("property");
            if ((property == null) || property.isEmpty()) {
                return FAIL;
            }
            char firstChar = property.charAt(0);
            if (Character.isUpperCase(firstChar)) {
                property = Character.toLowerCase(firstChar) + property.substring(1);
            }
            return new ActionMatcherResult(
                    this.matchesAction0(methodInvoker, methodInvoker.getParameterTypes()), property);
        }
    }
    return FAIL;
}

From source file:jp.co.opentone.bsol.framework.web.view.ExtendedJSON.java

public String getErrorPropertyName() {
    if (occured == null) {
        return null;
    }//  www  . j  a  va 2 s .co  m
    String msg = occured.getMessage();
    Matcher m = PROP_REGEX.matcher(msg);

    String result = null;
    if (m.matches() && m.groupCount() > 0) {
        result = m.group(1);
    }
    log.debug("errorPropertyName={}", result);
    return result;
}

From source file:org.apache.cxf.dosgi.topologymanager.ListenerHookImpl.java

private String getClassNameFromFilter(String filter) {
    if (filter != null) {
        Matcher matcher = CLASS_NAME_PATTERN.matcher(filter);
        if (matcher.matches() && matcher.groupCount() >= 1) {
            return matcher.group(1);
        }//w w w.  jav  a2 s  . c o m
    }
    return null;
}