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:logdruid.ui.table.EventRecordingEditorTable.java

public void FixValues() {
    String patternString = "";
    Matcher matcher = null;
    PatternCache patternCache = new PatternCache();
    Iterator it = data.iterator();
    Object[] obj;//ww w .j a  v  a  2  s  .c  om

    while (it.hasNext()) {
        obj = (Object[]) it.next();
        String stBefore = (String) obj[1];
        String stType = (String) obj[2];
        String stAfter = (String) obj[4];
        logger.info("stType: " + stType);
        if (stType.equals("date") && rep.getDateFormat(recording.getDateFormatID()).getPattern() != null) {
            patternString += stBefore + "(" + rep.getDateFormat(recording.getDateFormatID()).getPattern() + ")"
                    + stAfter;
            logger.info("getTypeString(stType) getPattern -: "
                    + rep.getDateFormat(recording.getDateFormatID()).getPattern());
            logger.info("getTypeString(stType) getDateFormat -: "
                    + rep.getDateFormat(recording.getDateFormatID()).getDateFormat());
        } else {
            patternString += stBefore + "(" + DataMiner.getTypeString(stType) + ")" + stAfter;
            logger.info("getTypeString(stType) -: " + DataMiner.getTypeString(stType));
        }
    }

    try {
        logger.info("theLine: " + examplePane.getText());
        logger.info("patternString: " + patternString);
        Highlighter h = examplePane.getHighlighter();
        h.removeAllHighlights();
        int currIndex = 0;

        String[] lines = examplePane.getText().split(System.getProperty("line.separator"));
        if (lines.length >= 1) {
            for (int i = 0; i < lines.length; i++) {
                matcher = patternCache.getPattern(patternString).matcher(lines[i]);
                if (matcher.find()) {
                    // int currIndex = 0;
                    // doc.insertString(doc.getLength(),line+"\n", null);

                    for (int i2 = 1; i2 <= matcher.groupCount(); i2++) {
                        model.setValueAt(matcher.group(i2), i2 - 1, 6);
                        h.addHighlight(currIndex + matcher.start(i2), +currIndex + matcher.end(i2),
                                new DefaultHighlighter.DefaultHighlightPainter(Color.ORANGE));
                    }
                }
                logger.info("currIndex: " + currIndex + "matcher.end(i2): " + lines[i].length() + ",l: "
                        + lines[i]);
                currIndex += lines[i].length() + 1;
            }
        }

    } catch (Exception e1) {
        e1.printStackTrace();
        // System.exit(1);
    }

}

From source file:com.gargoylesoftware.htmlunit.javascript.regexp.HtmlUnitRegExpProxy.java

private Object doAction(final Context cx, final Scriptable scope, final Scriptable thisObj, final Object[] args,
        final int actionType) {
    // in a first time just improve replacement with a String (not a function)
    if (RA_REPLACE == actionType && args.length == 2 && (args[1] instanceof String)) {
        final String thisString = Context.toString(thisObj);
        String replacement = (String) args[1];
        final Object arg0 = args[0];
        if (arg0 instanceof String) {
            replacement = REPLACE_PATTERN.matcher(replacement).replaceAll("\\$");
            // arg0 should *not* be interpreted as a RegExp
            return StringUtils.replaceOnce(thisString, (String) arg0, replacement);
        } else if (arg0 instanceof NativeRegExp) {
            try {
                final NativeRegExp regexp = (NativeRegExp) arg0;
                final RegExpData reData = new RegExpData(regexp);
                final String regex = reData.getJavaPattern();
                final int flags = reData.getJavaFlags();
                final Pattern pattern = Pattern.compile(regex, flags);
                final Matcher matcher = pattern.matcher(thisString);
                return doReplacement(thisString, replacement, matcher, reData.hasFlag('g'));
            } catch (final PatternSyntaxException e) {
                LOG.warn(e.getMessage(), e);
            }//from   w  ww.  j  ava  2  s  . co  m
        }
    } else if (RA_MATCH == actionType || RA_SEARCH == actionType) {
        if (args.length == 0) {
            return null;
        }
        final Object arg0 = args[0];
        final String thisString = Context.toString(thisObj);
        final RegExpData reData;
        if (arg0 instanceof NativeRegExp) {
            reData = new RegExpData((NativeRegExp) arg0);
        } else {
            reData = new RegExpData(Context.toString(arg0));
        }

        final Pattern pattern = Pattern.compile(reData.getJavaPattern(), reData.getJavaFlags());
        final Matcher matcher = pattern.matcher(thisString);

        final boolean found = matcher.find();
        if (RA_SEARCH == actionType) {
            if (found) {
                setProperties(matcher, thisString, matcher.start(), matcher.end());
                return matcher.start();
            }
            return -1;
        }

        if (!found) {
            return null;
        }
        final int index = matcher.start(0);
        final List<Object> groups = new ArrayList<>();
        if (reData.hasFlag('g')) { // has flag g
            groups.add(matcher.group(0));
            setProperties(matcher, thisString, matcher.start(0), matcher.end(0));

            while (matcher.find()) {
                groups.add(matcher.group(0));
                setProperties(matcher, thisString, matcher.start(0), matcher.end(0));
            }
        } else {
            for (int i = 0; i <= matcher.groupCount(); i++) {
                Object group = matcher.group(i);
                if (group == null) {
                    group = Context.getUndefinedValue();
                }
                groups.add(group);
            }

            setProperties(matcher, thisString, matcher.start(), matcher.end());
        }
        final Scriptable response = cx.newArray(scope, groups.toArray());
        // the additional properties (cf ECMA script reference 15.10.6.2 13)
        response.put("index", response, Integer.valueOf(index));
        response.put("input", response, thisString);
        return response;
    }

    return wrappedAction(cx, scope, thisObj, args, actionType);
}

From source file:org.apache.oozie.cli.OozieCLI.java

private String maskDate(Date date, String timeZoneId, boolean verbose) {
    if (date == null) {
        return "-";
    }//from  w w  w  .  j  av a 2 s. co m

    SimpleDateFormat dateFormater = null;
    if (verbose) {
        dateFormater = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss zzz", Locale.US);
    } else {
        dateFormater = new SimpleDateFormat("yyyy-MM-dd HH:mm zzz", Locale.US);
    }

    if (timeZoneId != null) {
        dateFormater.setTimeZone(TimeZone.getTimeZone(timeZoneId));
    }
    String dateString = dateFormater.format(date);
    // Most TimeZones are 3 or 4 characters; GMT offsets (e.g. GMT-07:00) are 9, so lets remove the "GMT" part to make it 6
    // to fit better
    Matcher m = GMT_OFFSET_SHORTEN_PATTERN.matcher(dateString);
    if (m.matches() && m.groupCount() == 2) {
        dateString = m.group(1) + m.group(2);
    }
    return dateString;
}

From source file:net.sf.logsaw.dialect.pattern.APatternDialect.java

@Override
public void parse(ILogResource log, InputStream input, ILogEntryCollector collector) throws CoreException {
    Assert.isNotNull(log, "log"); //$NON-NLS-1$
    Assert.isNotNull(input, "input"); //$NON-NLS-1$
    Assert.isNotNull(collector, "collector"); //$NON-NLS-1$
    Assert.isTrue(isConfigured(), "Dialect should be configured by now"); //$NON-NLS-1$
    try {/*from w  ww  . j  a  v  a2  s  .  co m*/
        LogEntry currentEntry = null;
        IHasEncoding enc = (IHasEncoding) log.getAdapter(IHasEncoding.class);
        IHasLocale loc = (IHasLocale) log.getAdapter(IHasLocale.class);
        if (loc != null) {
            // Apply the locale
            getPatternTranslator().applyLocale(loc.getLocale(), rules);
        }
        IHasTimeZone tz = (IHasTimeZone) log.getAdapter(IHasTimeZone.class);
        if (tz != null) {
            // Apply the timezone
            getPatternTranslator().applyTimeZone(tz.getTimeZone(), rules);
        }
        LineIterator iter = IOUtils.lineIterator(input, enc.getEncoding());
        int minLinesPerEntry = getPatternTranslator().getMinLinesPerEntry();
        int lineNo = 0;
        int moreLinesToCome = 0;
        try {
            String line = null;
            while (iter.hasNext()) {
                lineNo++;

                if (minLinesPerEntry == 1) {
                    // Simple case
                    line = iter.nextLine();
                } else {
                    String s = iter.nextLine();
                    if (moreLinesToCome == 0) {
                        Matcher m = getInternalPatternFirstLine().matcher(s);
                        if (m.find()) {
                            // First line
                            line = s;
                            moreLinesToCome = minLinesPerEntry - 1;
                            continue;
                        } else {
                            // Some crazy stuff
                            line = s;
                        }
                    } else if (iter.hasNext() && (moreLinesToCome > 1)) {
                        // Some middle line
                        line += IOUtils.LINE_SEPARATOR + s;
                        moreLinesToCome--;
                        continue;
                    } else {
                        // Last line
                        line += IOUtils.LINE_SEPARATOR + s;
                        if (!iter.hasNext()) {
                            line += IOUtils.LINE_SEPARATOR;
                        }
                        moreLinesToCome = 0;
                    }
                }

                // Error handling
                List<IStatus> statuses = null;
                boolean fatal = false; // determines whether to interrupt parsing

                Matcher m = getInternalPatternFull().matcher(line);
                if (m.find()) {
                    // The next line matches, so flush the previous entry and continue
                    if (currentEntry != null) {
                        collector.collect(currentEntry);
                        currentEntry = null;
                    }
                    currentEntry = new LogEntry();
                    for (int i = 0; i < m.groupCount(); i++) {
                        try {
                            getPatternTranslator().extractField(currentEntry, getRules().get(i),
                                    m.group(i + 1));
                        } catch (CoreException e) {
                            // Mark for interruption
                            fatal = fatal || e.getStatus().matches(IStatus.ERROR);

                            // Messages will be displayed later
                            if (statuses == null) {
                                statuses = new ArrayList<IStatus>();
                            }
                            if (e.getStatus().isMultiStatus()) {
                                Collections.addAll(statuses, e.getStatus().getChildren());
                            } else {
                                statuses.add(e.getStatus());
                            }
                        }
                    }

                    // We encountered errors or warnings
                    if (statuses != null && !statuses.isEmpty()) {
                        currentEntry = null; // Stop propagation
                        IStatus status = new MultiStatus(PatternDialectPlugin.PLUGIN_ID, 0,
                                statuses.toArray(new IStatus[statuses.size()]),
                                NLS.bind(Messages.APatternDialect_error_failedToParseLine, lineNo), null);
                        if (fatal) {
                            // Interrupt parsing in case of error
                            throw new CoreException(status);
                        } else {
                            collector.addMessage(status);
                        }
                    }
                } else if (currentEntry != null) {
                    // Append to message
                    String msg = currentEntry.get(getFieldProvider().getMessageField());
                    currentEntry.put(getFieldProvider().getMessageField(), msg + IOUtils.LINE_SEPARATOR + line);
                }

                if (collector.isCanceled()) {
                    // Cancel parsing
                    break;
                }
            }

            if (currentEntry != null) {
                // Collect left over entry
                collector.collect(currentEntry);
            }
        } finally {
            LineIterator.closeQuietly(iter);
        }
    } catch (Exception e) {
        throw new CoreException(new Status(IStatus.ERROR, PatternDialectPlugin.PLUGIN_ID,
                NLS.bind(Messages.APatternDialect_error_failedToParseFile,
                        new Object[] { log.getName(), e.getLocalizedMessage() }),
                e));
    }
}

From source file:lcmc.cluster.ui.ClusterBrowser.java

/**
 * Return volume info object from the drbd block device name.
 * /dev/drbd/by-res/r0//from  www  .  java 2  s. c o  m
 * /dev/drbd/by-res/r0/0
 * /dev/drbd0
 */
public VolumeInfo getDrbdVolumeFromDev(final CharSequence dev) {
    if (dev == null) {
        return null;
    }
    final Matcher m = DEV_DRBD_BY_RES_PATTERN.matcher(dev);
    if (m.matches()) {
        final String res = m.group(1);
        final String vol;
        if (m.groupCount() > 2) {
            vol = m.group(2);
        } else {
            vol = "0";
        }
        final ResourceInfo dri = getDrbdResourceNameHash().get(res);
        putDrbdResHash();
        if (dri != null) {
            return dri.getDrbdVolumeInfo(vol);
        }
    }
    return null;
}

From source file:com.tao.realweb.util.StringUtil.java

/** 
* ************************************************************************* 
* ?????,?? //from w  w w . j ava 2  s .c  o m
*  
* @param str 
*            ? 
* @param pattern 
*            ? 
* @return ? 
*/

// ?pattern?  
// java.util.regex????  
public static String[] getStringArrayByPattern(String str, String pattern) {
    Pattern p = Pattern.compile(pattern, Pattern.CASE_INSENSITIVE);
    Matcher matcher = p.matcher(str);
    //   
    Set<String> result = new HashSet<String>();// ?? ???  
    // boolean find() ???  
    while (matcher.find()) {
        for (int i = 0; i < matcher.groupCount(); i++) { // int groupCount()  
                                                         // ???  
                                                         // System.out.println(matcher.group(i));  
            result.add(matcher.group(i));

        }
    }
    String[] resultStr = null;
    if (result.size() > 0) {
        resultStr = new String[result.size()];
        return result.toArray(resultStr);// Set resultString[] resultStr  
    }
    return resultStr;

}

From source file:lcmc.gui.ClusterBrowser.java

/**
 * Return volume info object from the drbd block device name.
 * /dev/drbd/by-res/r0//w ww . j  ava  2  s. co  m
 * /dev/drbd/by-res/r0/0
 * /dev/drbd0
 */
public DrbdVolumeInfo getDrbdVolumeFromDev(final String dev) {
    if (dev == null) {
        return null;
    }
    final Matcher m = BY_RES_PATTERN.matcher(dev);
    if (m.matches()) {
        final String res = m.group(1);
        String vol;
        if (m.groupCount() > 2) {
            vol = m.group(2);
        } else {
            vol = "0";
        }
        final DrbdResourceInfo dri = getDrbdResHash().get(res);
        putDrbdResHash();
        if (dri != null) {
            return dri.getDrbdVolumeInfo(vol);
        }
    }
    return null;
}

From source file:csiro.pidsvc.mappingstore.Manager.java

public String resolveLookupValue(String ns, String key) {
    LookupMapDescriptor lookupDescriptor = getLookupMapType(ns);
    if (lookupDescriptor == null)
        return null;

    try {// ww w  .jav  a 2s.c o  m
        if (lookupDescriptor.isStatic()) {
            String ret = getLookupValue(ns, key);
            return ret == null ? lookupDescriptor.getDefaultValue(key) : ret;
        } else if (lookupDescriptor.isHttpResolver()) {
            final Pattern reType = Pattern.compile("^T:(.+)$", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE);
            final Pattern reExtract = Pattern.compile("^E:(.+)$", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE);
            final Pattern reNamespace = Pattern.compile("^NS:(.+?):(.+)$",
                    Pattern.CASE_INSENSITIVE | Pattern.MULTILINE);
            Matcher m;
            String endpoint, extractorType, extractor, content;
            String[] dynKeyValue = getLookupKeyValue(ns);

            if (dynKeyValue == null)
                return null;

            // Endpoint.
            endpoint = dynKeyValue[0];
            if (endpoint.contains("$0"))
                endpoint = endpoint.replace("$0", key);
            else
                endpoint += key;

            // Type.
            m = reType.matcher(dynKeyValue[1]);
            m.find();
            extractorType = m.group(1);

            // Extractor.
            m = reExtract.matcher(dynKeyValue[1]);
            m.find();
            extractor = m.group(1);

            // Execute HTTP GET request.
            content = Http.simpleGetRequestStrict(endpoint);
            if (content == null)
                return lookupDescriptor.getDefaultValue(key);

            // Retrieve data.
            if (extractor.equals(""))
                return content;
            if (extractorType.equalsIgnoreCase("Regex")) {
                Pattern re = Pattern.compile(extractor);
                m = re.matcher(content);

                if (m.find())
                    return m.groupCount() > 0 ? m.group(1) : m.group();
            } else if (extractorType.equalsIgnoreCase("XPath")) {
                Processor processor = new Processor(false);
                XPathCompiler xpathCompiler = processor.newXPathCompiler();

                // Declare XML namespaces.
                m = reNamespace.matcher(dynKeyValue[1]);
                while (m.find())
                    xpathCompiler.declareNamespace(m.group(1), m.group(2));

                // Evaluate XPath expression.
                XdmItem node = xpathCompiler.evaluateSingle(extractor,
                        processor.newDocumentBuilder().build(new StreamSource(new StringReader(content))));
                return node == null ? lookupDescriptor.getDefaultValue(key) : node.getStringValue();
            }
        }
    } catch (Exception e) {
        _logger.error(e);
    }
    return lookupDescriptor.getDefaultValue(key);
}

From source file:logdruid.util.DataMiner.java

public static Map<String, ArrayList<FileRecord>> getSourceFileGroup(Map<Integer, FileRecord> sourceFiles,
        Source src, Repository repo) {
    PatternCache patternCache = new PatternCache();
    String patternString = "";
    Map<String, ArrayList<FileRecord>> sourceFileGroup = new HashMap<String, ArrayList<FileRecord>>();
    ArrayList<FileRecord> groupedFiles = new ArrayList<FileRecord>();
    // ArrayList<SourceItem> sourceItemArrayList = src.getSourceItem();
    ArrayList<Recording> recordings = (ArrayList<Recording>) repo.getRecordings(MetadataRecording.class);
    Matcher matcher = null;
    if (recordings != null) {
        Iterator<Recording> it = recordings.iterator();
        // logger.info("recordings not null ");
        while (it.hasNext()) {
            Recording rec = it.next();/*from  w  ww  .  ja  va  2 s  .co  m*/
            if (src.isActiveRecordingOnSource(rec)) {
                ArrayList<RecordingItem> rIV = ((MetadataRecording) rec).getRecordingItem();
                Iterator<RecordingItem> itV = rIV.iterator();
                int nbRec = 0;
                while (itV.hasNext()) {
                    RecordingItem rI = itV.next();
                    String type = rI.getType();
                    if (type == "date") {
                        patternString += rI.getBefore() + "(" + repo.getDateFormat(rec.getDateFormatID()) + ")"
                                + rI.getAfter();
                    } else {
                        patternString += rI.getBefore() + "(" + DataMiner.getTypeString(type) + ")"
                                + rI.getAfter();
                    }
                    // logger.info("patternString: " + patternString
                    // + " getType: " +
                    // DataMiner.getTypeString(rI.getType()));
                    nbRec++;
                }
                Iterator<FileRecord> sourceFileIterator = sourceFiles.values().iterator();
                String key = "";
                // tempV = new ArrayList<String>();
                while (sourceFileIterator.hasNext()) {
                    groupedFiles.clear();

                    FileRecord fileName = sourceFileIterator.next();
                    // logger.info("file: "+fileName);
                    try {

                        if (logger.isDebugEnabled())
                            logger.debug("patternString: " + patternString);
                        if (logger.isDebugEnabled())
                            logger.debug("filename: " + fileName);
                        // Pattern pattern = Pattern.compile(patternString +
                        // ".*");
                        // Matcher matcher = pattern.matcher(fileName);
                        matcher = patternCache.getPattern(patternString + ".*")
                                .matcher(new File(repo.getBaseSourcePath()).toURI()
                                        .relativize(new File(fileName.getFile().getCanonicalPath()).toURI())
                                        .getPath());
                        //***
                        if (matcher.find()) {
                            if (logger.isDebugEnabled())
                                logger.debug("found filename " + fileName + " with group");

                            key = "";
                            int i = 1;
                            for (i = 1; i <= matcher.groupCount(); i++) {
                                if (recordings.get(i).getIsActive()) {
                                    if (logger.isDebugEnabled())
                                        logger.debug("one : " + matcher.group(i));
                                    key += matcher.group(i) + " ";
                                }
                            }
                            if (logger.isDebugEnabled())
                                logger.debug("i : " + i + " nbRec: " + nbRec);
                            if (i - 1 == nbRec) {
                                if (logger.isDebugEnabled())
                                    logger.debug(" passed!");
                                if (!sourceFileGroup.containsKey(key)) {
                                    ArrayList<FileRecord> v = new ArrayList<FileRecord>();
                                    v.add(fileName);
                                    sourceFileGroup.put(key, v);
                                    if (logger.isDebugEnabled())
                                        logger.debug(" to key: " + key + " added : " + fileName);
                                } else {
                                    sourceFileGroup.get(key).add(fileName);
                                    if (logger.isDebugEnabled())
                                        logger.debug(" to key: " + key + " added : " + fileName);

                                }

                            }
                            /*
                             * if (tempV != null) { sourceFileGroup.put(key,
                             * tempV); logger.info("Added file " + fileName
                             * + " to group " + key.toString());
                             * logger.info("files " + tempV);
                             * 
                             * }
                             */
                        }

                    } catch (Exception e1) {
                        e1.printStackTrace();
                        // System.exit(1);
                    }

                    // logger.info("found group " + key + "with " +
                    // groupedFiles.size() + " files in source " +
                    // src.getSourceName());

                }
            }
        }
    }
    // TODO Auto-generated method stub
    return sourceFileGroup;
}

From source file:de.uni_koblenz.jgralab.utilities.rsa2tg.Rsa2Tg.java

/**
 * Creates {@link EdgeClass} names for all EdgeClass objects, which do have
 * an empty String or a String, which ends with a '.'.
 *//*from  w  ww.j a  v a 2s .  c o  m*/
private void createEdgeClassNames() {
    System.out.println("Creating missing edge class names...");
    for (EdgeClass ec : sg.getEdgeClassVertices()) {
        String name = ec.get_qualifiedName().trim();

        // invent an edgeclass name
        String ecName = null;

        Matcher m = GENNAME_PATTERN.matcher(name);
        if (m.matches()) {
            name = m.group(1);
            ecName = m.group(m.groupCount());
        }

        if (!name.equals("") && !name.endsWith(".")) {
            continue;
        }

        IncidenceClass to = (IncidenceClass) ec.getFirstGoesToIncidence().getThat();
        IncidenceClass from = (IncidenceClass) ec.getFirstComesFromIncidence().getThat();

        String toRole = to.get_roleName();
        if ((toRole == null) || toRole.equals("")) {
            toRole = ((VertexClass) to.getFirstEndsAtIncidence().getThat()).get_qualifiedName();
            int p = toRole.lastIndexOf('.');
            if (p >= 0) {
                toRole = toRole.substring(p + 1);
            }
        } else {
            toRole = Character.toUpperCase(toRole.charAt(0)) + toRole.substring(1);
        }

        // There must be a 'to' role name, which is different than null and
        // not empty.
        if ((toRole == null) || (toRole.length() <= 0)) {
            throw new ProcessingException(getFilename(),
                    "There is no role name 'to' for the edge '" + name + "' defined.");
        }

        if (ecName == null) {
            if ((from.get_aggregation() != AggregationKind.NONE)
                    || (to.get_aggregation() != AggregationKind.NONE)) {
                if (to.get_aggregation() != AggregationKind.NONE) {
                    ecName = "Contains" + toRole;
                } else {
                    ecName = "IsPartOf" + toRole;
                }
            } else {
                ecName = "LinksTo" + toRole;
            }
        } else {
            ecName += toRole;
        }

        if (isUseFromRole()) {
            String fromRole = from.get_roleName();
            if ((fromRole == null) || fromRole.equals("")) {
                fromRole = ((VertexClass) from.getFirstEndsAtIncidence().getThat()).get_qualifiedName();
                int p = fromRole.lastIndexOf('.');
                if (p >= 0) {
                    fromRole = fromRole.substring(p + 1);
                }
            } else {
                fromRole = Character.toUpperCase(fromRole.charAt(0)) + fromRole.substring(1);
            }

            // There must be a 'from' role name, which is different than
            // null and not empty.
            if ((fromRole == null) || (fromRole.length() <= 0)) {
                throw new ProcessingException(getFilename(),
                        "There is no role name of 'from' for the edge '" + name + "' defined.");
            }
            name += fromRole;
        }

        assert (ecName != null) && (ecName.length() > 0);
        ec.set_qualifiedName(name + ecName);
    }
}