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:com.android.screenspeak.formatter.EventSpeechRule.java

/**
 * Returns a resource identifier from the given <code>context</code> for the text
 * content of a <code>node</code>.
 * <p>/*from   w  ww .  j av a  2 s.  com*/
 * Note: The resource identifier format is: @&lt;package
 * name&gt;:&lt;type&gt;/&lt;resource name&gt;
 * </p>
 *
 * @param context The parent context.
 * @param resName A valid resource name.
 * @return A resource identifier, or {@code -1} if the resource name is
 *         invalid.
 */
private static int getResourceIdentifierContent(Context context, String resName) {
    if (resName == null) {
        return -1;
    }

    final Matcher matcher = mResourceIdentifier.matcher(resName);

    if (!matcher.matches()) {
        return -1;
    }

    final Resources res = context.getResources();
    final String defaultPackage = (matcher.groupCount() < 2) ? context.getPackageName() : null;
    final int resId = res.getIdentifier(resName.substring(1), null, defaultPackage);

    if (resId == 0) {
        LogUtils.log(EventSpeechRule.class, Log.ERROR, "Failed to load resource: %s", resName);
    }

    return resId;
}

From source file:com.redhat.red.offliner.alist.PomArtifactListReader.java

public PomArtifactListReader(final File settingsXml, final String typeMappingFile,
        final CredentialsProvider creds) {
    this.settingsXml = settingsXml;
    this.creds = creds;

    Properties props = new Properties();
    if (StringUtils.isEmpty(typeMappingFile)) {
        try (InputStream mappingStream = getClass().getClassLoader()
                .getResourceAsStream(DEFAULT_TYPE_MAPPING_RES)) {
            props.load(mappingStream);// w w w.  java2s. co m
        } catch (IOException ex) {
            throw new IllegalStateException("Failed to load Maven type mapping from default properties", ex);
        }
    } else {
        try (InputStream mappingStream = new FileInputStream(typeMappingFile)) {
            props.load(mappingStream);
        } catch (IOException ex) {
            throw new IllegalStateException(
                    "Failed to load Maven type mapping provided properties file " + typeMappingFile, ex);
        }
    }
    this.typeMapping = new HashMap<>(props.size());

    Pattern p = Pattern.compile("([^:]+)(?::(.+))?");
    for (Map.Entry<Object, Object> entry : props.entrySet()) {
        String type = (String) entry.getKey();

        String value = (String) entry.getValue();
        Matcher m = p.matcher(value);
        if (!m.matches()) {
            throw new IllegalArgumentException(
                    "The type mapping string \"" + typeMappingFile + "\" has a wrong format.");
        }
        String extension = m.group(1);
        if (m.groupCount() == 2) {
            String classifier = m.group(2);
            this.typeMapping.put(type, new TypeMapping(extension, classifier));
        } else {
            this.typeMapping.put(type, new TypeMapping(extension));
        }
    }
}

From source file:org.herrlado.websms.connector.magtifunge.ConnectorMagtifun.java

/**
 * Push SMS Free Count to WebSMS./* ww w  .  j  a  v a 2 s  . com*/
 * 
 * @param ctx
 *            {@link ConnectorContext}
 * @param content
 *            conten to investigate.
 */
private void notifyFreeCount(final ConnectorContext ctx, final String content) {
    final Matcher m = BALANCE_MATCH_PATTERN.matcher(content);
    String term = null;
    if (m.find()) {
        if (m.groupCount() != 2) {
            term = "?";
        } else {
            term = m.group(1) + "+" + m.group(2) + "";
        }
    } else {
        Log.w(TAG, content);
        term = "?";
    }
    this.getSpec(ctx.getContext()).setBalance(term);
}

From source file:org.apache.jmeter.gui.action.Save.java

/**
 * <p>//  ww  w.j a va  2 s  .com
 * Create a backup copy of the specified file whose name will be
 * <code>{baseName}-{version}.jmx</code><br>
 * Where :<br>
 * <code>{baseName}</code> is the name of the file to backup without its
 * <code>.jmx</code> extension. For a file named <code>testplan.jmx</code>
 * it would then be <code>testplan</code><br>
 * <code>{version}</code> is the version number automatically incremented
 * after the higher version number of pre-existing backup files. <br>
 * <br>
 * Example: <code>testplan-000028.jmx</code> <br>
 * <br>
 * If <code>jmeter.gui.action.save.backup_directory</code> is <b>not</b>
 * set, then backup files will be created in
 * <code>${JMETER_HOME}/backups</code>
 * </p>
 * <p>
 * Backup process is controlled by the following jmeter/user properties :<br>
 * <table border=1>
 * <tr>
 * <th align=left>Property</th>
 * <th align=left>Type/Value</th>
 * <th align=left>Description</th>
 * </tr>
 * <tr>
 * <td><code>jmeter.gui.action.save.backup_on_save</code></td>
 * <td><code>true|false</code></td>
 * <td>Enables / Disables backup</td>
 * </tr>
 * <tr>
 * <td><code>jmeter.gui.action.save.backup_directory</code></td>
 * <td><code>/path/to/backup/directory</code></td>
 * <td>Set the directory path where backups will be stored upon save. If not
 * set then backups will be created in <code>${JMETER_HOME}/backups</code><br>
 * If that directory does not exist, it will be created</td>
 * </tr>
 * <tr>
 * <td><code>jmeter.gui.action.save.keep_backup_max_hours</code></td>
 * <td><code>integer</code></td>
 * <td>Maximum number of hours to preserve backup files. Backup files whose
 * age exceeds that limit should be deleted and will be added to this method
 * returned list</td>
 * </tr>
 * <tr>
 * <td><code>jmeter.gui.action.save.keep_backup_max_count</code></td>
 * <td><code>integer</code></td>
 * <td>Max number of backup files to be preserved. Exceeding backup files
 * should be deleted and will be added to this method returned list. Only
 * the most recent files will be preserved.</td>
 * </tr>
 * </table>
 * </p>
 * 
 * @param fileToBackup
 *            The file to create a backup from
 * @return A list of expired backup files selected according to the above
 *         properties and that should be deleted after the save operation
 *         has performed successfully
 */
private List<File> createBackupFile(File fileToBackup) {
    if (!BACKUP_ENABLED || !fileToBackup.exists()) {
        return EMPTY_FILE_LIST;
    }
    char versionSeparator = '-'; //$NON-NLS-1$
    String baseName = fileToBackup.getName();
    // remove .jmx extension if any
    baseName = baseName.endsWith(JMX_FILE_EXTENSION)
            ? baseName.substring(0, baseName.length() - JMX_FILE_EXTENSION.length())
            : baseName;
    // get a file to the backup directory
    File backupDir = new File(BACKUP_DIRECTORY);
    backupDir.mkdirs();
    if (!backupDir.isDirectory()) {
        log.error(
                "Could not backup file ! Backup directory does not exist, is not a directory or could not be created ! <" //$NON-NLS-1$
                        + backupDir.getAbsolutePath() + ">"); //$NON-NLS-1$
    }

    // select files matching
    // {baseName}{versionSeparator}{version}{jmxExtension}
    // where {version} is a 6 digits number
    String backupPatternRegex = Pattern.quote(baseName + versionSeparator) + "([\\d]{6})" //$NON-NLS-1$
            + Pattern.quote(JMX_FILE_EXTENSION);
    Pattern backupPattern = Pattern.compile(backupPatternRegex);
    // create a file filter that select files matching a given regex pattern
    IOFileFilter patternFileFilter = new PrivatePatternFileFilter(backupPattern);
    // get all backup files in the backup directory
    List<File> backupFiles = new ArrayList<>(FileUtils.listFiles(backupDir, patternFileFilter, null));
    // find the highest version number among existing backup files (this
    // should be the more recent backup)
    int lastVersionNumber = 0;
    for (File backupFile : backupFiles) {
        Matcher matcher = backupPattern.matcher(backupFile.getName());
        if (matcher.find() && matcher.groupCount() > 0) {
            // parse version number from the backup file name
            // should never fail as it matches the regex
            int version = Integer.parseInt(matcher.group(1));
            lastVersionNumber = Math.max(lastVersionNumber, version);
        }
    }
    // find expired backup files
    List<File> expiredFiles = new ArrayList<>();
    if (BACKUP_MAX_HOURS > 0) {
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.HOUR_OF_DAY, -BACKUP_MAX_HOURS);
        long expiryDate = cal.getTime().getTime();
        // select expired files that should be deleted
        IOFileFilter expiredFileFilter = FileFilterUtils.ageFileFilter(expiryDate, true);
        expiredFiles.addAll(FileFilterUtils.filterList(expiredFileFilter, backupFiles));
    }
    // sort backups from by their last modified time
    Collections.sort(backupFiles, new Comparator<File>() {
        @Override
        public int compare(File o1, File o2) {
            long diff = o1.lastModified() - o2.lastModified();
            // convert the long to an int in order to comply with the method
            // contract
            return diff < 0 ? -1 : diff > 0 ? 1 : 0;
        }
    });
    // backup name is of the form
    // {baseName}{versionSeparator}{version}{jmxExtension}
    String backupName = baseName + versionSeparator + BACKUP_VERSION_FORMATER.format(lastVersionNumber + 1)
            + JMX_FILE_EXTENSION;
    File backupFile = new File(backupDir, backupName);
    // create file backup
    try {
        FileUtils.copyFile(fileToBackup, backupFile);
    } catch (IOException e) {
        log.error("Failed to backup file :" + fileToBackup.getAbsolutePath(), e); //$NON-NLS-1$
        return EMPTY_FILE_LIST;
    }
    // add the fresh new backup file (list is still sorted here)
    backupFiles.add(backupFile);
    // unless max backups is not set, ensure that we don't keep more backups
    // than required
    if (BACKUP_MAX_COUNT > 0 && backupFiles.size() > BACKUP_MAX_COUNT) {
        // keep the most recent files in the limit of the specified max
        // count
        expiredFiles.addAll(backupFiles.subList(0, backupFiles.size() - BACKUP_MAX_COUNT));
    }
    return expiredFiles;
}

From source file:org.appspot.apprtc.DirectRTCClient.java

/**
 * Connects to the room.//from  ww  w  .  ja va  2  s  .  co m
 *
 * Runs on the looper thread.
 */
private void connectToRoomInternal() {
    this.roomState = ConnectionState.NEW;

    String endpoint = connectionParameters.roomId;

    Matcher matcher = IP_PATTERN.matcher(endpoint);
    if (!matcher.matches()) {
        reportError("roomId must match IP_PATTERN for DirectRTCClient.");
        return;
    }

    String ip = matcher.group(1);
    String portStr = matcher.group(matcher.groupCount());
    int port;

    if (portStr != null) {
        try {
            port = Integer.parseInt(portStr);
        } catch (NumberFormatException e) {
            reportError("Invalid port number: " + portStr);
            return;
        }
    } else {
        port = DEFAULT_PORT;
    }

    tcpClient = new TCPChannelClient(executor, this, ip, port);
}

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

/**
 * Checks the file or directory passed to determine if it should be excluded
 * from the scan/*from www.  j a  v  a2 s  .c  o  m*/
 *
 * @param srcPath
 * @param file
 * @return boolean flag, true if the file should be excluded, false
 * otherwise
 */
protected boolean isFiltered(MediaLibraryPath srcPath, File file) {
    boolean isDirectory = file.isDirectory();
    String filename = file.getName();

    // Skip these parts if the file is a directory
    if (!isDirectory) {
        int index = filename.lastIndexOf('.');
        if (index < 0) {
            return true;
        }

        String extension = file.getName().substring(index + 1).toUpperCase();
        if (!supportedExtensions.contains(extension)) {
            return true;
        }

        // Exclude files without external subtitles
        if (StringUtils.isBlank(opensubtitles)) {
            // We are not downloading subtitles, so exclude those that don't have any.
            if (excludeFilesWithoutExternalSubtitles && !hasSubtitles(file)) {
                LOG.info("File {} excluded. (no external subtitles)", filename);
                return true;
            }
        }
    }

    // Compute the relative filename
    String relativeFilename = file.getAbsolutePath().substring(mediaLibraryRootPathIndex);

    String relativeFileNameLower = relativeFilename.toLowerCase();
    String jukeboxName = PropertiesUtil.getProperty("mjb.detailsDirName", "Jukebox");

    for (String excluded : srcPath.getExcludes()) {
        if (excluded.length() > 0) {
            try {
                Pattern excludePatt = Pattern.compile(excluded, Pattern.CASE_INSENSITIVE);
                if (excludePatt.matcher(relativeFileNameLower).find()) {
                    LOG.debug("{} '{}' excluded.", isDirectory ? "Directory" : "File", relativeFilename);
                    return true;
                }
            } catch (Exception error) {
                LOG.info("Error processing exclusion pattern: {}, {}", excluded, error.getMessage());
            }

            excluded = excluded.replace("/", File.separator);
            excluded = excluded.replace("\\", File.separator);
            if (relativeFileNameLower.contains(excluded.toLowerCase())) {
                // Don't print a message for the exclusion of Jukebox files
                if (!relativeFileNameLower.contains(jukeboxName)) {
                    LOG.debug("{} '{}' excluded.", isDirectory ? "Directory" : "File", relativeFilename);
                }
                return true;
            }
        }
    }

    // Handle special case of RARs. If ".rar", and it is ".partXXX.rar"
    // exclude all NON-"part001.rar" files.
    Matcher m = PATTERN_RAR_PART.matcher(relativeFileNameLower);

    if (m.find() && (m.groupCount() == 1)) {
        if (Integer.parseInt(m.group(1)) != 1) {
            LOG.debug("Excluding file '{}' as it is a non-first part RAR archive ({})", relativeFilename,
                    m.group(1));
            return true;
        }
    }

    return false;
}

From source file:org.andrewberman.sync.PDFSearcher.java

ArrayList<String> handleArticlePage(String body) throws Exception {
    ArrayList<String> outLinks = new ArrayList<String>();

    Matcher m;
    for (int i = 0; i < linkPatterns.size(); i++) {
        Pattern p = linkPatterns.get(i);
        m = p.matcher(body);/*from w ww.jav a2s.  c  om*/
        if (m.find()) {
            outLinks.add(m.group(m.groupCount()));
        }
    }

    /*
     * Special case: Look for a direct PDF link within the "Fulltext article" links.
     */
    Pattern p = RegexUtils.grabUntilClosingElement("div", RegexUtils.createPattern("view fulltext"));
    m = p.matcher(body);
    while (m.find()) {
        String s = m.group();
        Pattern p2 = RegexUtils.hrefRegex("pdf");
        Matcher m2 = p2.matcher(s);
        while (m2.find()) {
            String couldbePDF = m2.group(m2.groupCount());
            outLinks.add(0, couldbePDF);
        }
    }

    return outLinks;
}

From source file:net.kautler.teamcity.sourceforge.SourceForgeIssueFetcher.java

/**
 * Retrieve the custom value for some field from the specified ticket.
 * <p/>//from ww  w.j  a v  a 2s . c  o m
 * Allowed syntax for the field value:
 * <p><dl>
 * <dt><b>labels:&lt;regex&gt;[:&lt;default&gt;]</b></dt>
 * <dd>
 * The value is defined by one or more labels.<br/>
 * If multiple labels are found, they are joined together with commas.<br/>
 * If no label is found, the default value is used, if one is defined.<br/>
 * The regex must not contain any colons. If you need to match a colon, use '\u005c003a' instead.
 * <ul>
 * <li>If no regex is given, all labels are used, e.&nbsp;g. 'labels:' or 'labels::bug'</li>
 * <li>
 * If a regex without group is given, all labels matching the regex are used completely,
 * e.&nbsp;g. 'labels:.+_bug' or 'labels:.+_bug:general_bug'<bs:help file="Integrating+TeamCity+with+Issue+Tracker"/>
 * </li>
 * <li>
 * If a regex with groups is given, all labels matching the regex are used, but only their first group,
 * e.&nbsp;g. 'labels:type_(.+)' or 'labels:type_(.+):bug'<bs:help file="Integrating+TeamCity+with+Issue+Tracker"/>
 * </li>
 * </ul>
 * </dd>
 * <dt><b>custom:&lt;custom field name&gt;[:&lt;default&gt;]</b></dt>
 * <dd>
 * The value is defined by the value of a custom field, e.&nbsp;g. 'custom:_type' or 'custom:_type:bug'<br/>
 * If the custom field is not found, not set or empty, the default value is used, if one is defined.
 * </dd>
 * <dt><b>&lt;fixed string&gt;</b></dt>
 * <dd>All issues have the same value defined here, e.&nbsp;g. 'bug'</dd>
 * </dl>
 *
 * @param fieldValue the custom value field specification
 * @param ticket     the ticket to retrieve the data from
 * @return the retrieved custom value
 */
@Nullable
private String getCustomValue(@NotNull String fieldValue, @NotNull Ticket ticket) {
    String[] fieldValueParts = fieldValue.split(":", 3);

    // if there is no colon, this is the fixed string case, so simple return the specification
    if (fieldValueParts.length == 1) {
        return fieldValue;
    }

    if (fieldValueParts[0].equals("labels")) {
        String labelRegex = fieldValueParts[1];
        if (isEmpty(labelRegex)) {
            // if no regex is given, just use all labels
            String labels = join(ticket.getLabels().iterator(), ", ");
            if (isNotBlank(labels)) {
                return labels;
            }
            // if there are no labels present, return the default value if specified
            if (fieldValueParts.length > 2) {
                return fieldValueParts[2];
            }
        } else {
            // if there is a regex given, search all matching labels
            Pattern labelPattern = safeCompilePattern(labelRegex);
            List<String> matchingLabels = new ArrayList<String>();
            for (String label : ticket.getLabels()) {
                Matcher labelMatcher = labelPattern.matcher(label);
                if (labelMatcher.matches()) {
                    // use the first group if present, or the whole match otherwise
                    if (labelMatcher.groupCount() > 0) {
                        matchingLabels.add(labelMatcher.group(1));
                    } else {
                        matchingLabels.add(labelMatcher.group());
                    }
                }
            }
            // join the matched labels together
            String labels = join(matchingLabels.iterator(), ", ");
            if (isNotBlank(labels)) {
                return labels;
            }
            // if no labels were found, return the default value if specified
            if (fieldValueParts.length > 2) {
                return fieldValueParts[2];
            }
        }
    } else if (fieldValueParts[0].equals("custom")) {
        String customFieldValue = ticket.getCustomFields().get(fieldValueParts[1]);
        if (isNotBlank(customFieldValue)) {
            return customFieldValue;
        }
        // if the custom field is not found, not set or empty, return the default value if specified
        if (fieldValueParts.length > 2) {
            return fieldValueParts[2];
        }
    } else {
        // there is a colon present, but none of the defined prefixes matches,
        // so we are in the fixed string case again, simply return specification
        return fieldValue;
    }

    return null;
}

From source file:de.pixida.logtest.logreaders.GenericLogReader.java

private String getMatch(final Matcher matcher, final Integer groupIndex) {
    if (groupIndex > matcher.groupCount()) {
        throw new LogReaderException("Tried to extract matching group '" + groupIndex
                + "' but pattern gave only '" + matcher.groupCount() + "' matches");
    }/* w ww. j a v a  2  s  . co  m*/
    return matcher.group(groupIndex);
}

From source file:org.cesecore.util.TimeUnitFormat.java

/**
 * Parses a formatted time string.//from  ww  w .j  a  v a 2  s .c  o  m
 * 
 * @param formatted
 *            time string, i.e '1y-2mo10d'.
 * @return the milliseconds as long value from 0.
 * @throws ParseException
 *             if the string cannot be parsed, i.e. it contains units not
 *             listed or other illegal characters or forms.
 */
public long parseMillis(String formattedString) throws NumberFormatException {
    NumberFormatException exception = null;
    long result = 0;
    if (StringUtils.isNotBlank(formattedString)) {
        formattedString = formattedString.trim();
        final Matcher matcher = pattern.matcher(formattedString);
        long parsedValue;
        String unit = null;
        int start = 0, end = 0;
        while (matcher.find()) {
            start = matcher.start();
            if (start != end) {
                exception = new NumberFormatException(EXCEPTION_MESSAGE_ILLEGAL_CHARACTERS);
                break;
            }
            end = matcher.end();
            for (int i = 0; i < matcher.groupCount(); i = i + 3) {
                parsedValue = Long.parseLong(matcher.group(i + 2));
                unit = matcher.group(i + 3).toLowerCase();
                result += factors.get(unit) * parsedValue;
            }
        }
        if (end != formattedString.length()) {
            exception = new NumberFormatException(EXCEPTION_MESSAGE_ILLEGAL_CHARACTERS);
        }

    } else {
        exception = new NumberFormatException(EXCEPTION_MESSAGE_BLANK_STRING);
    }
    if (null != exception) {
        throw exception;
    }
    return result;
}