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.thinkbiganalytics.nifi.feedmgr.ConfigurationPropertyReplacer.java

/**
 * @param property         the NifiProperty to replace
 * @param configProperties a Map of properties which will be looked to to match against the property key
 *///from   w  ww  .j ava 2 s .co  m
public static boolean resolveStaticConfigurationProperty(NifiProperty property,
        Map<String, Object> configProperties) {
    String value = property.getValue();
    StringBuffer sb = null;

    if (configProperties != null && !configProperties.isEmpty()) {

        if (StringUtils.isNotBlank(value)) {
            Pattern variablePattern = Pattern.compile("\\$\\{(.*?)\\}");
            Matcher matchVariablePattern = variablePattern.matcher(value);
            while (matchVariablePattern.find()) {
                if (sb == null) {
                    sb = new StringBuffer();
                }
                String group = matchVariablePattern.group();
                int groupCount = matchVariablePattern.groupCount();
                if (groupCount == 1) {

                    String variable = matchVariablePattern.group(1);
                    //lookup the variable
                    //first look at configuration properties
                    Object resolvedValue = configProperties.get(variable);
                    if (resolvedValue != null) {
                        matchVariablePattern.appendReplacement(sb, resolvedValue.toString());
                    }
                }
            }
            if (sb != null) {
                matchVariablePattern.appendTail(sb);
            }
        }
    }

    if (sb == null) {

        String updatedValue = resolveValue(property, configProperties);
        if (StringUtils.isNotBlank(updatedValue)) {
            sb = new StringBuffer();
            sb.append(updatedValue);
        }

    }
    if (sb != null) {
        property.setValue(StringUtils.trim(sb.toString()));
    }

    return sb != null;
}

From source file:at.gv.egiz.sl.util.BKUSLConnector.java

public static SLPdfAsException generateLegacySLException(String xmlResponse) {
    if (xmlResponse != null) {
        if (xmlResponse.contains("ErrorResponse")) {
            int errorCode = -1;
            String errorInfo = null;
            // Probably an ErrorResponse
            Pattern patternErrorCode = Pattern.compile(PATTERN_ERROR_CODE, Pattern.CASE_INSENSITIVE);
            Matcher matcherErrorCode = patternErrorCode.matcher(xmlResponse);
            if (matcherErrorCode.find()) {
                if (matcherErrorCode.groupCount() == 1) {
                    String errorCodeString = matcherErrorCode.group(1);
                    try {
                        errorCode = Integer.parseInt(errorCodeString);
                    } catch (NumberFormatException e) {
                        // Ignore
                        logger.trace("Failed to convert ErrorCode [{}] into number", errorCodeString);
                    }//w  w w.j a  v a2s .com
                }
            }

            if (errorCode > 0) {

                Pattern patternErrorInfo = Pattern.compile(PATTERN_ERROR_INFO, Pattern.CASE_INSENSITIVE);
                Matcher matcherErrorInfo = patternErrorInfo.matcher(xmlResponse);

                if (matcherErrorInfo.find()) {
                    if (matcherErrorInfo.groupCount() == 1) {
                        errorInfo = matcherErrorInfo.group(1);
                    }
                }

                return new SLPdfAsException(errorCode, errorInfo);
            }
        }
    }
    return null;
}

From source file:net.krautchan.data.KCPosting.java

public static String sanitizeContent(String inContent) {
    String locContent = inContent;
    locContent = StringEscapeUtils.unescapeHtml4(locContent);
    locContent = locContent.replaceAll("<p>", "");
    locContent = locContent.replaceAll("</p>", " ");

    locContent = locContent.replaceAll("onclick=\"highlightPost\\(\\'\\d+\\'\\);\"", "");
    locContent = locContent.replaceAll(">>>(\\d+)</a>",
            " onclick='quoteClick(this); return false;' class=\"kclink\">&gt;&gt; $1</a>");

    locContent = locContent.replaceAll("<a href=\"/resolve(/.+?)\"\\s*>.+?</a>",
            "<a href=\"/resolve$1\" class=\"kclink\" onclick=\"Android.openKcLink('$1');return false;\">&gt;&gt; $1</a>");
    Matcher m = linkPat.matcher(locContent);
    StringBuffer buf = new StringBuffer(locContent.length() + 1000);
    int end = 0;//from   www  .j  a v a 2 s  .  c  o m
    while (m.find()) {
        int gc = m.groupCount();
        if (gc > 0) {
            buf.append(locContent.substring(end, m.start()));
            end = m.end();
            String host = m.group(1);
            String name = host;
            String styleClass = "extlink";
            String androidFunction = "openExternalLink";
            String url = m.group(1) + "/" + m.group(2);
            if ((host.contains("youtube")) || (host.contains("youtu.be"))) {
                styleClass = "ytlink";
                name = "YouTube";
                androidFunction = "openYouTubeVideo";
            } else if (host.contains("krautchan.net")) {
                styleClass = "kclink";
                name = ">>";
                host = "";
                androidFunction = "openKcLink";
            }
            buf.append("<a href=\"http://" + m.group(1) + "/" + m.group(2) + "\" class=\"" + styleClass
                    + "\" onclick=\"Android." + androidFunction + "('" + url + "');return false;\">" + name
                    + "</a>" + m.group(3));
        }
    }
    buf.append(locContent.substring(end, locContent.length()));
    return "<p><span>" + buf.toString().trim() + "</span></p>";
}

From source file:de.micromata.tpsb.doc.parser.JavaDocUtil.java

/**
 * Parst einen JavaDoc Tag/*from w w  w . ja  va2 s . co m*/
 * 
 * @param tag der Tag-String
 * @param tagMap die zu befllende Tag-Map
 */
private static void parseTag(String tag, Map<String, List<Pair<String, String>>> tagMap) {
    final String TUPEL_PATTERN = "^(%s)(.*)$";
    final String TRIPEL_PATTERN = "^(@\\S*)\\s(\\S*)(.*)$";
    int idx = StringUtils.indexOf(tag, " ");
    String tagName = StringUtils.substring(tag, 0, idx);

    String pattern = tupelTags.contains(tagName) ? TUPEL_PATTERN : TRIPEL_PATTERN;
    Pattern p = Pattern.compile(String.format(pattern, tagName), Pattern.DOTALL);
    Matcher matcher = p.matcher(tag);
    String key = null;
    String val = null;
    if (matcher.matches() == true) {
        switch (matcher.groupCount()) {
        case 2:
            val = matcher.group(2).trim();
            break;
        case 3:
            key = matcher.group(2).trim();
            val = matcher.group(3).trim();
            break;
        default:
            System.out.println("Kein Match");
        }
        if (tagMap.get(tagName) == null) {
            tagMap.put(tagName, new ArrayList<Pair<String, String>>());
        }
        tagMap.get(tagName).add(Pair.make(key, val));
    }
}

From source file:io.jari.geenstijl.API.API.java

private static Artikel parseArtikel(Element artikel_el, Context context) throws ParseException {
    Artikel artikel = new Artikel();

    //id// w  w w . java 2  s  . c o  m
    artikel.id = Integer.parseInt(artikel_el.attr("id").substring(1));

    //summary
    artikel.summary = artikel_el.select("a.more").first() != null;

    //titel
    artikel.titel = artikel_el.select("h1").text();

    //plaatje
    if (PreferenceManager.getDefaultSharedPreferences(context).getBoolean("show_images", true)) {
        Element plaatje = artikel_el.select("img").first();
        if (plaatje != null) {
            try {
                String url = plaatje.attr("src");
                Log.d(TAG, "Downloading " + url);
                //                    artikel.plaatje = Drawable.createFromStream(((java.io.InputStream)new URL(plaatje.attr("src")).getContent()), null);
                artikel.plaatje = readBytes((InputStream) new URL(plaatje.attr("src")).getContent());
                artikel.groot_plaatje = plaatje.hasClass("groot");
                if (plaatje.hasAttr("width") && plaatje.hasAttr("height"))
                    if (!plaatje.attr("width").equals("100") || !plaatje.attr("height").equals("100"))
                        artikel.groot_plaatje = true;
                if (artikel.groot_plaatje)
                    Log.i(TAG, "    Done. Big image.");
                else
                    Log.i(TAG, "    Done.");
            } catch (Exception ex) {
                Log.w(TAG, "Unable to download image, Falling back... Reason: " + ex.getMessage());
                artikel.plaatje = null;
            }
        }
    }

    //embed
    if (artikel_el.select("div.embed").first() != null) {
        //atm alleen support voor iframes
        Element frame = artikel_el.select("div.embed>iframe").first();
        if (frame != null)
            artikel.embed = frame.attr("src");
    }

    //embed (geenstijl.tv)
    if (!domain.equals("www.geenstijl.nl")) {
        //extract url from script
        Element scriptEl = artikel_el.select("script").first();
        if (scriptEl != null) {
            String script = scriptEl.html();
            Pattern pattern = Pattern.compile("'(.*)', fall");
            Matcher matcher = pattern.matcher(script);
            if (matcher.find() && matcher.groupCount() == 1) {
                artikel.embed = matcher.group(1);
            }
        }
    }

    //footer shit
    Element footer = artikel_el.select("footer").first();
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm", Locale.US);
    artikel.datum = simpleDateFormat.parse(footer.select("time").first().attr("datetime"));

    StringTokenizer footer_items = new StringTokenizer(footer.text(), "|");
    artikel.auteur = footer_items.nextToken().trim();

    artikel.reacties = Integer.parseInt(footer.select("a.comments").text().replace(" reacties", ""));

    artikel.link = footer.select("a").first().attr("href");

    //clean up
    artikel_el.select("h1").remove();
    artikel_el.select(".embed").remove();
    artikel_el.select("img").remove();
    artikel_el.select("footer").remove();
    artikel_el.select("a.more").remove();
    artikel_el.select("script").remove();

    //inhoud
    artikel.inhoud = artikel_el.html();

    return artikel;
}

From source file:br.gov.frameworkdemoiselle.ldap.internal.ClazzUtils.java

/**
 * Feeling a Class or return null for a String Representation of Search
 * Filters (RFC 4515)/*from   w ww .  j  a v a  2 s. co m*/
 * 
 * @param searchFilter
 * @return Class
 */
public static Class<?> getClassForSearchFilter(String searchFilter, List<String> packageNames) {
    if (searchFilter == null || packageNames == null || packageNames.size() == 0)
        return null;
    String patternStr = "objectClass=(.*?)(\\)|$)";
    Matcher matcher = Pattern.compile(patternStr).matcher(searchFilter);
    boolean matchFound = matcher.find();
    if (matchFound && matcher.groupCount() > 1)
        for (String packageName : packageNames)
            try {
                return Class.forName(packageName + "." + Character.toUpperCase(matcher.group(1).charAt(0))
                        + matcher.group(1).substring(1));
            } catch (Exception e) {
            }
    return null;
}

From source file:nl.mpcjanssen.simpletask.util.Util.java

public static DateTime addInterval(DateTime date, String interval) {
    Pattern p = Pattern.compile("(\\d+)([dwmy])");
    Matcher m = p.matcher(interval.toLowerCase());
    int amount;/*ww w . jav a 2s.c  om*/
    String type;
    if (date == null) {
        date = new DateTime();
    }
    m.find();
    if (m.groupCount() == 2) {
        amount = Integer.parseInt(m.group(1));
        type = m.group(2).toLowerCase();
    } else {
        return null;
    }
    Period period = new Period(0);
    if (type.equals("d")) {
        period = period.plusDays(amount);
    } else if (type.equals("w")) {
        period = period.plusWeeks(amount);
    } else if (type.equals("m")) {
        period = period.plusMonths(amount);
    } else if (type.equals("y")) {
        period = period.plusYears(amount);
    }
    return date.plus(period);
}

From source file:ai.susi.mind.SusiInference.java

/**
 * "see" defines a new thought based on the names given in the "transferExpr" and retrieved using the content of
 * a variable in the "expr" expression using a matching in the given pattern. It can be used to check if something
 * learned in the flow matches against a known pattern. When the matching is successful, that defines a new knowledge
 * pieces that are stored in the resulting thought thus extending an argument with new insights.
 * The "transferExpr" must be constructed using variables of the name schema "%1%", "%2%", .. which contain matches
 * of the variables from the expr retrieval in the flow with the pattern.
 * @param flow the argument flow/*from w ww .j  a v a  2s . c  om*/
 * @param transferExpr SQL-like transfer expression, like "a AS akk, b AS bit". These defined variables stored in the flow as next thought
 * @param expr the name of a variable entity in the argument flow. The content of that variable is matched in the pattern
 * @param pattern the
 * @return a new thought containing variables from the matcher in the pattern
 */
private static final SusiThought see(SusiArgument flow, String transferExpr, String expr, Pattern pattern) {
    // example: see $1$ as idea from ""
    SusiThought nextThought = new SusiThought();
    try {
        Matcher m = pattern.matcher(flow.unify(expr, 0));
        int gc = -1;
        if (new TimeoutMatcher(m).matches()) {
            SusiTransfer transfer = new SusiTransfer(transferExpr);
            JSONObject choice = new JSONObject();
            if ((gc = m.groupCount()) > 0) {
                for (int i = 0; i < gc; i++)
                    choice.put("%" + (i + 1) + "%", m.group(i));
            } else {
                choice.put("%1%", expr);
            }
            JSONObject seeing = transfer.extract(choice);
            for (String key : seeing.keySet()) {
                String observed = seeing.getString(key);
                nextThought.addObservation(key, observed);
            }
        }
    } catch (PatternSyntaxException e) {
        e.printStackTrace();
    }
    return nextThought; // an empty thought is a fail signal
}

From source file:me.vertretungsplan.parser.UntisInfoParser.java

@NotNull
static List<String> parseClasses(String navbarDoc, JSONObject data) throws JSONException, IOException {
    Pattern pattern = Pattern.compile("var classes = (\\[[^\\]]*\\]);");
    Matcher matcher = pattern.matcher(navbarDoc);
    if (matcher.find()) {
        JSONArray classesJson = new JSONArray(matcher.group(1));
        List<String> classes = new ArrayList<>();
        for (int i = 0; i < classesJson.length(); i++) {
            String className = classesJson.getString(i);
            if (data.optString(PARAM_CLASS_SELECT_REGEX, null) != null) {
                Pattern classNamePattern = Pattern.compile(data.getString(PARAM_CLASS_SELECT_REGEX));
                Matcher classNameMatcher = classNamePattern.matcher(className);
                if (classNameMatcher.find()) {
                    if (classNameMatcher.groupCount() > 0) {
                        StringBuilder builder = new StringBuilder();
                        for (int j = 1; j <= classNameMatcher.groupCount(); j++) {
                            if (classNameMatcher.group(j) != null) {
                                builder.append(classNameMatcher.group(j));
                            }/*  w  ww.j a v a2  s.c o m*/
                        }
                        className = builder.toString();
                    } else {
                        className = classNameMatcher.group();
                    }
                } else if (data.optBoolean(PARAM_REMOVE_NON_MATCHING_CLASSES, false)) {
                    continue;
                }
            }
            classes.add(className);
        }
        return classes;
    } else {
        throw new IOException();
    }
}

From source file:com.jabyftw.easiercommands.Util.java

/**
 * Source: Essentials (found through Ban-Management)
 * <b>Letters used:</b> y mo w d h m s
 *
 * @param time string with the time, eg: "3w4h" - three weeks and four hours
 * @return the time in milliseconds//from   ww w  .  j  a v a  2  s. c  om
 * @see <a href=https://github.com/BanManagement/BanManager/blob/master/src/main/java/me/confuser/banmanager/util/DateUtils.java>Credits to Essentials</a>
 */
public static long parseTimeDifference(@NotNull String time) {
    Pattern timePattern = Pattern.compile("(?:([0-9]+)\\s*y[a-z]*[,\\s]*)?" + "(?:([0-9]+)\\s*mo[a-z]*[,\\s]*)?"
            + "(?:([0-9]+)\\s*w[a-z]*[,\\s]*)?" + "(?:([0-9]+)\\s*d[a-z]*[,\\s]*)?"
            + "(?:([0-9]+)\\s*h[a-z]*[,\\s]*)?" + "(?:([0-9]+)\\s*m[a-z]*[,\\s]*)?"
            + "(?:([0-9]+)\\s*(?:s[a-z]*)?)?", Pattern.CASE_INSENSITIVE);
    Matcher matcher = timePattern.matcher(time);

    int years = 0, months = 0, weeks = 0, days = 0, hours = 0, minutes = 0, seconds = 0;
    boolean found = false;

    while (matcher.find()) {
        if (matcher.group() == null || matcher.group().isEmpty()) {
            continue;
        }

        for (int i = 0; i < matcher.groupCount(); i++) {
            if (matcher.group(i) != null && !matcher.group(i).isEmpty()) {
                found = true;
                break;
            }
        }

        if (found) {
            if (matcher.group(1) != null && !matcher.group(1).isEmpty())
                years = Integer.parseInt(matcher.group(1));
            if (matcher.group(2) != null && !matcher.group(2).isEmpty())
                months = Integer.parseInt(matcher.group(2));
            if (matcher.group(3) != null && !matcher.group(3).isEmpty())
                weeks = Integer.parseInt(matcher.group(3));
            if (matcher.group(4) != null && !matcher.group(4).isEmpty())
                days = Integer.parseInt(matcher.group(4));
            if (matcher.group(5) != null && !matcher.group(5).isEmpty())
                hours = Integer.parseInt(matcher.group(5));
            if (matcher.group(6) != null && !matcher.group(6).isEmpty())
                minutes = Integer.parseInt(matcher.group(6));
            if (matcher.group(7) != null && !matcher.group(7).isEmpty())
                seconds = Integer.parseInt(matcher.group(7));
            break;
        }
    }

    if (!found)
        throw new IllegalArgumentException("Date can't be parsed");
    if (years > 20)
        throw new IllegalArgumentException("Date is too big");

    Calendar calendar = new GregorianCalendar();

    if (years > 0)
        calendar.add(Calendar.YEAR, years);
    if (months > 0)
        calendar.add(Calendar.MONTH, months);
    if (weeks > 0)
        calendar.add(Calendar.WEEK_OF_YEAR, weeks);
    if (days > 0)
        calendar.add(Calendar.DAY_OF_MONTH, days);
    if (hours > 0)
        calendar.add(Calendar.HOUR_OF_DAY, hours);
    if (minutes > 0)
        calendar.add(Calendar.MINUTE, minutes);
    if (seconds > 0)
        calendar.add(Calendar.SECOND, seconds);

    return calendar.getTimeInMillis() - System.currentTimeMillis();
}