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:jef.tools.string.RegexpUtils.java

/**
 * ?/*from   www.j av  a2s.co  m*/
 * @param pattern ?
 * @param str     
 * @param strict  ??????
 * @return        ?null
 */
public static String[] getMatcherResult(String str, String regexp, boolean strict) {
    if (!strict) {
        String tmp = StringUtils.remove(str, "\\(");
        tmp = StringUtils.remove(str, "\\)");
        if (tmp.indexOf('(') > -1 && tmp.indexOf(')') > -1) {
            //??
        } else {
            regexp = "(" + regexp + ")";//
        }
    }
    Matcher m = getMatcher(str, regexp, strict);
    if (!m.matches())
        return null;
    int n = m.groupCount();
    if (n == 0)
        return new String[] { m.group() };
    String[] result = new String[n];
    for (int i = 1; i <= n; i++) {
        result[i - 1] = m.group(i);
    }
    return result;
}

From source file:com.espertech.esper.pattern.observer.TimerScheduleISO8601Parser.java

private static void parsePeriodTimePart(String timePart, TimePeriod timePeriod)
        throws ScheduleParameterException {
    Pattern pattern = Pattern.compile("(\\d+H)?(\\d+M)?(\\d+S)?");
    Matcher matcher = pattern.matcher(timePart);
    if (!matcher.matches()) {
        throw new IllegalStateException();
    }//from ww w.  j a va2s . com
    for (int i = 0; i < matcher.groupCount(); i++) {
        String group = matcher.group(i + 1);
        if (group == null) {
        } else if (group.endsWith("H")) {
            timePeriod.setHours(safeParsePrefixedInt(group));
        } else if (group.endsWith("M")) {
            timePeriod.setMinutes(safeParsePrefixedInt(group));
        } else if (group.endsWith("S")) {
            timePeriod.setSeconds(safeParsePrefixedInt(group));
        }
    }
}

From source file:com.espertech.esper.pattern.observer.TimerScheduleISO8601Parser.java

private static void parsePeriodDatePart(String datePart, TimePeriod timePeriod)
        throws ScheduleParameterException {
    Pattern pattern = Pattern.compile("(\\d+Y)?(\\d+M)?(\\d+W)?(\\d+D)?");
    Matcher matcher = pattern.matcher(datePart);
    if (!matcher.matches()) {
        throw new IllegalStateException();
    }//from  w w w  .ja  v  a 2  s.  c om
    for (int i = 0; i < matcher.groupCount(); i++) {
        String group = matcher.group(i + 1);
        if (group == null) {
        } else if (group.endsWith("Y")) {
            timePeriod.setYears(safeParsePrefixedInt(group));
        } else if (group.endsWith("M")) {
            timePeriod.setMonths(safeParsePrefixedInt(group));
        } else if (group.endsWith("D")) {
            timePeriod.setDays(safeParsePrefixedInt(group));
        } else if (group.endsWith("W")) {
            timePeriod.setWeeks(safeParsePrefixedInt(group));
        }
    }
}

From source file:com.technophobia.substeps.model.Arguments.java

public static String[] getArgs(final String patternString, final String sourceString,
        final String[] keywordPrecedence, Config cfg) {

    log.debug("Arguments getArgs String[] with pattern: " + patternString + " and sourceStr: " + sourceString);

    String[] rtn = null;/* ww w .j  a  va  2s  .c  o  m*/

    ArrayList<String> argsList = null;

    String patternCopy = patternString;
    if (keywordPrecedence != null && StringUtils.startsWithAny(patternString, keywordPrecedence)) {
        //
        for (String s : keywordPrecedence) {

            patternCopy = StringUtils.removeStart(patternCopy, s);
        }

        patternCopy = "(?:" + StringUtils.join(keywordPrecedence, "|") + ")" + patternCopy;
    }

    final Pattern pattern = Pattern.compile(patternCopy);
    final Matcher matcher = pattern.matcher(sourceString);

    final int groupCount = matcher.groupCount();

    // TODO - this doesn't work if we're not doing strict matching
    if (matcher.find()) {

        for (int i = 1; i <= groupCount; i++) {
            final String arg = substituteValues(matcher.group(i), cfg);

            if (arg != null) {
                if (argsList == null) {
                    argsList = new ArrayList<>();
                }
                argsList.add(arg);
            }
        }
    }

    if (argsList != null) {
        rtn = argsList.toArray(new String[argsList.size()]);

        if (log.isDebugEnabled()) {

            final StringBuilder buf = new StringBuilder();
            buf.append("returning args: ");

            for (final String s : argsList) {

                buf.append("[").append(s).append("] ");
            }

            log.debug(buf.toString());
        }

    }

    return rtn;
}

From source file:com.manydesigns.elements.util.Util.java

public static void printMatcher(Matcher matcher) {
    for (int i = 0; i <= matcher.groupCount(); i++) {
        logger.debug("group {}: {}", i, matcher.group(i));
    }/* ww w  . ja v  a 2s.  c  o  m*/
}

From source file:com.revolsys.ui.html.domain.PhoneNumber.java

/**
 * Parse a phone number using the regular expression and if it matches the
 * phone number, format it using the specified format otherwise return null.
 *
 * @param phoneNumber The normalized phone number to format.
 * @param regex The regular expression to match phone numbers.
 * @param format The format specification.
 * @return The formatted phone number./*from  w ww  .  j av  a2s  . c  om*/
 */
public static String format(final String phoneNumber, final String regex, final String format) {
    if (phoneNumber != null && regex != null && format != null) {
        final Pattern pattern = Pattern.compile(regex);
        final Matcher matcher = pattern.matcher(phoneNumber);
        if (matcher.matches()) {
            final Map values = new HashMap();
            for (int i = 1; i <= matcher.groupCount(); i++) {
                values.put("n" + i, matcher.group(i));
            }
            Expression expression;
            try {
                expression = JexlUtil.newExpression(format);
            } catch (final Exception e) {
                throw new IllegalArgumentException(
                        regex + " is not a valid regular expression: " + e.getMessage());
            }
            final HashMapContext context = new HashMapContext();
            context.setVars(values);
            try {
                return (String) expression.evaluate(context);
            } catch (final Exception e) {
                throw new IllegalArgumentException(format + " is not a valid format: " + e.getMessage());
            }
        }
    }
    return null;
}

From source file:com.networknt.mask.Mask.java

private static String replaceWithMask(String stringToBeMasked, char maskingChar, String regex) {
    if (stringToBeMasked.length() == 0) {
        return stringToBeMasked;
    }//from w  w  w  . j a  v a2s. c o m
    String replacementString = "";
    String padGroup = "";
    if (!StringUtils.isEmpty(regex)) {
        try {
            Pattern pattern = patternCache.get(regex);
            if (pattern == null) {
                pattern = Pattern.compile(regex);
                patternCache.put(regex, pattern);
            }
            Matcher matcher = pattern.matcher(stringToBeMasked);
            if (matcher.matches()) {
                String currentGroup = "";
                for (int i = 0; i < matcher.groupCount(); i++) {
                    currentGroup = matcher.group(i + 1);
                    padGroup = StringUtils.rightPad("", currentGroup.length(), maskingChar);
                    stringToBeMasked = StringUtils.replace(stringToBeMasked, currentGroup, padGroup, 1);
                }
                replacementString = stringToBeMasked;
            }
        } catch (Exception e) {
            replacementString = StringUtils.rightPad("", stringToBeMasked.length(), maskingChar);
        }
    } else {
        replacementString = StringUtils.rightPad("", stringToBeMasked.length(), maskingChar);
    }
    return replacementString;
}

From source file:de.egore911.versioning.deployer.performer.PerformExtraction.java

/**
 * Returns the matching part of the entry's name.
 * /*from  ww  w.  jav  a2s  . c  o  m*/
 * FIXME assumes that the '*' is only used for matching files, not
 * directories!
 */
private static String getSourcePatternMatch(String entryName, String sourcePattern) {

    // Create a regular expression pattern for the given sourcePattern
    Pattern pattern = patternCache.get(sourcePattern);
    if (pattern == null) {
        // Pattern compilation is expensive, so cache it
        pattern = Pattern.compile(transformSourcePatternToRegularExpression(sourcePattern));
        patternCache.put(sourcePattern, pattern);
    }

    // Perform the actual replacement
    Matcher matcher = pattern.matcher(entryName);
    StringBuffer buffer = new StringBuffer();
    if (matcher.matches()) {
        if (matcher.groupCount() == 1) {
            matcher.appendReplacement(buffer, matcher.group(1));
        }
    }
    matcher.appendTail(buffer);
    return buffer.toString();
}

From source file:org.adl.datamodels.DMTimeUtility.java

/**
 * This method takes the input String parameter which represents
 * a datamodel time interval string and converts it to an array of integers.
 * The array integers represent the years, months, days, hours, minutes, 
 * seconds and decimal portions of seconds of the input time interval 
 * string.  Any on of the time interval sections may be missing
 * //  w w  w.  j av  a 2  s .  c o m
 * @param iTime The String representation of a datamodel time interval.
 * 
 * @param ioArray An array of integers.
 * 
 */
private static void timeStringParse(String iTime, int[] ioArray) {
    // P[yY][mM][dD][T[hH][mM][s[.s]S] 
    // P1Y3M2DT3H
    // PT3H5M

    Matcher matcher = TIME_STRING_PATTERN.matcher(iTime);
    if (matcher.matches()) {
        for (int i = 0; i < ioArray.length; i++) {
            if (i < matcher.groupCount()) {
                String value = matcher.group(i + 1);
                ioArray[i] = ((StringUtils.isNotEmpty(value) && StringUtils.isNumeric(value))
                        ? Integer.parseInt(value)
                        : 0);
            }
        }
    }
}

From source file:com.vmware.o11n.plugin.crypto.model.CryptoUtil.java

/**
 * Sometimes the line endings can unintentially get stripped by a user in the vRO client.
 * This function attempts to rebuild a PEM string with the expected line length and line endings
 *
 * @param pem/*from   w  w  w  .  j  ava  2s  .co  m*/
 *
 * returns a properly formed PEM string
 */
public static String fixPemString(String pem) {

    final Pattern pemP = Pattern
            .compile(FIVE_DASH + "(.*)" + FIVE_DASH + "([\\s\\S]*)" + FIVE_DASH + "(.*)" + FIVE_DASH);
    final Matcher pemM = pemP.matcher(pem);

    String header = "";
    String data = "";
    String footer = "";

    if (pemM.find() && pemM.groupCount() == 3) {
        header = pemM.group(1).trim();
        data = pemM.group(2).trim();
        footer = pemM.group(3).trim();
    } else {
        log.error(
                "Could not parse pem parts. Either the RegEx couldn't find a PEM format or the 3 parts of a PEM couldn't be found.");
        throw new RuntimeException("Could not parse pem parts");
    }
    ArrayList<String> dataParts = splitOnNumChars(data, 64);

    StringBuilder newPem = new StringBuilder();

    newPem.append(FIVE_DASH).append(header).append(FIVE_DASH).append("\n");
    for (String part : dataParts) {
        newPem.append(part).append("\n");
    }
    newPem.append(FIVE_DASH).append(footer).append(FIVE_DASH);

    return newPem.toString();
}