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.nttec.everychan.ui.presentation.HtmlParser.java

private static int parseColor(String css) {
    if (TextUtils.isEmpty(css))
        return 0;
    try {// ww  w  .j a  va  2 s  . c  om
        Matcher m = CSS_STYLE_COLOR_RGB_PATTERN.matcher(css);
        if (m.find() && m.groupCount() == 3) {
            int n1 = Integer.parseInt(m.group(1));
            int n2 = Integer.parseInt(m.group(2));
            int n3 = Integer.parseInt(m.group(3));
            return Color.rgb(n1, n2, n3);
        }
        m = CSS_STYLE_COLOR_COMMON_PATTERN.matcher(css);
        if (m.find() && m.groupCount() == 1) {
            return Color.parseColor(m.group(1));
        }
    } catch (Exception e) {
        /*?  ? ? (   ? )*/ }
    return 0;
}

From source file:com.thoughtworks.go.domain.DefaultCommentRenderer.java

private String id(Matcher matcher) {
    return matcher.groupCount() > 0 ? contentsOfFirstGroupThatMatched(matcher) : matcher.group();
}

From source file:br.com.capanema.kers.velocity.util.BuildManagerUtil.java

/**
 * Increment source code of filePath using template fragment.
 * //from   www  . j  a va2 s . co  m
 * @param filePath
 * @param incrementPath
 * @param incrementPattern
 * @param dataGroup
 */
public static void incrementSourceCode(String filePath, String incrementPath, String incrementPattern,
        String firstAfter, Map<String, String> params, TemplateDataGroup dataGroup) {
    try {
        HashMap<String, Object> velocityVariables = new HashMap<String, Object>(); //map for velocity variables
        velocityVariables.put("data", dataGroup); //conjunto de vriaveis que podem ser usados no template

        if (params != null && params.size() > 0) {
            /*            for (String name : params.keySet()) {
                           velocityVariables.put("params."+name, params.get(name));
                        }*/
            velocityVariables.put("params", params);
        }

        //rodando velocity do incremento
        TemplateEngine templateEngine = TemplateEngineFactory.getEngine(incrementPath, true);
        String incrementSource = templateEngine.runFile(incrementPath, velocityVariables);

        // Create the pattern
        Pattern pattern = Pattern.compile("[\r\n]*[\t]*" + incrementPattern, Pattern.DOTALL); //o "[\r\n]*"  para pegar as quebras de linhas que podem existir no incremento
        Matcher matcher = pattern.matcher("");

        //novo incremento
        //aqui vai executar o pattern no prprio incremento... se o pattern estiver errado no ir encontrar nada e vai abortar o incremento
        matcher.reset(incrementSource);
        Map<String, String[]> mapGroupIncrement = new LinkedHashMap<String, String[]>();
        while (matcher.find()) {
            String[] groups = new String[matcher.groupCount()];
            for (int i = 0; i < matcher.groupCount(); i++) {
                groups[i] = matcher.group(i + 1);
            }

            String increment = matcher.group(); //new increment
            mapGroupIncrement.put(increment, groups); //map increment vs groups
        }

        if (mapGroupIncrement.size() == 0) { //no encontrou groups no incremento (usado para as comparaes), aborta
            return;
        }

        //le o arquivo atual
        FileInputStream inputFilePath = new FileInputStream(filePath);
        BufferedInputStream bufferedInput = new BufferedInputStream(inputFilePath);
        StringBuffer filePathContent = new StringBuffer();
        int ch = 0;
        while ((ch = bufferedInput.read()) > -1) {
            filePathContent.append((char) ch);
        }
        inputFilePath.close();
        bufferedInput.close();

        //procura no arquivo todo pela expresso regular
        matcher = pattern.matcher("");
        matcher.reset(filePathContent);
        StringBuffer newContentFile = new StringBuffer();
        int countMatcher = 0;
        Map<String, String[]> mapGroupFile = new HashMap<String, String[]>();
        while (matcher.find()) { //verifica cada ocorrncia da expresso no arquivo
            String[] groups = new String[matcher.groupCount()]; //pega os groups "()" do matcher para fazer a comparao com os groups do incremento que est sendo gerado
            for (int i = 0; i < matcher.groupCount(); i++) {
                groups[i] = matcher.group(i + 1);
            }
            mapGroupFile.put(matcher.group(), groups); //adiciona esse group em uma lista para ser avaliado depois

            countMatcher++; //isso vai contar onde esta o ltimo matcher
        }

        //valida quais incrementos so realmente novos, comparando os groups
        List<String> newIncrements = new LinkedList<String>();
        for (String groupIncrement : mapGroupIncrement.keySet()) {
            String[] groups1 = mapGroupIncrement.get(groupIncrement); //groups do incremento
            boolean itemFound = false;

            for (String groupFile : mapGroupFile.keySet()) {
                String[] groups2 = mapGroupFile.get(groupFile); //groups do incremento

                if (ArrayUtil.equals(groups1, groups2)) { //se no arquivo tem o cdigo que est sendo gerado, no precisa adicionar esse incremnto
                    itemFound = true;
                }
            }
            if (!itemFound) { //se no arquivo no tem o cdigo que est sendo gerado, adiciona em um array
                newIncrements.add(groupIncrement);
            }
        }

        //realiza uma quebra de linha adicional para o primeiro item do incremento, para no ficar na mesma linha do ltimo matcher no arquivo
        StringBuffer newIncrementSource = new StringBuffer();
        int i = 0;
        for (String incremento : newIncrements) {
            if (i == 0 && incremento.indexOf("\r\n\r\n") != 0) { //s coloca quebra de linha se precisar
                newIncrementSource.append("\r\n");
            }

            newIncrementSource.append(incremento);
            i++;
        }

        if (newIncrements.size() > 0) {
            //no encontrou nenhum increment no arquivo, ento procura pelo firstAfter para inserir o primeiro incremento
            if (countMatcher == 0 && firstAfter != null && !firstAfter.equals("")) {
                pattern = Pattern.compile(firstAfter, Pattern.DOTALL);
                matcher = pattern.matcher("");
                matcher.reset(filePathContent);

                //esse loop s serviu para contar e achar o ltimo matcher. No consegui fazer sem isso :(
                countMatcher = 0;
                while (matcher.find()) { //verifica cada ocorrncia da expresso
                    countMatcher++;
                }
            }

            //aqui vou realmente substituir os valores, j sabendo qual  a ltima ocorrencia da palavra no arquivo
            i = 0;
            matcher.reset();
            while (matcher.find()) { //verifica cada ocorrncia da expresso
                i++;
                if (countMatcher == i) { //se encontrou a ltima ocorrencia
                    String matcherGroup = matcher.group();
                    matcher.appendReplacement(newContentFile, matcherGroup + newIncrementSource); //substitui a ultima ocorrencia do firstIncrement   
                }
            }
            matcher.appendTail(newContentFile);
        }

        //save new file
        if (newContentFile.length() > 0) {
            FileUtil.writeFile(filePath, newContentFile.toString());
        }
    } catch (Exception e) {
        // TODO: handle exception
        e.printStackTrace();
    }
}

From source file:com.thoughtworks.go.domain.DefaultCommentRenderer.java

private String contentsOfFirstGroupThatMatched(Matcher matcher) {
    for (int i = 1; i <= matcher.groupCount(); i++) {
        String groupContent = matcher.group(i);
        if (groupContent != null) {
            return groupContent;
        }//w  ww  . j a va 2  s  . c  o  m
    }
    return null;
}

From source file:com.agloco.util.StringUtil.java

public static String find(String source, String regex, int index) {
    String result = null;/*  w  w w.java 2s . c  o m*/
    if (source != null && regex != null) {
        Pattern p = Pattern.compile(regex);
        Matcher m = p.matcher(source);
        boolean find = m.find(0);
        result = (find && m.groupCount() >= index) ? m.group(index) : null;
    }
    return result;
}

From source file:com.agloco.util.StringUtil.java

public static String replace(String source, String regex, int index, String replacement) {
    StringBuffer result = new StringBuffer();
    if (source != null && regex != null) {
        Pattern p = Pattern.compile(regex);
        Matcher m = p.matcher(source);
        boolean find = m.find(0);
        if (find && m.groupCount() >= index) {
            if (m.start(index) > 0)
                result.append(source.substring(0, m.start(index)));
            result.append(replacement);//from  w  w w . j a v  a2  s . c  om
            if (m.end(index) < source.length())
                result.append(source.substring(m.end(index)));
        } else {
            result.append(source);
        }
    }
    return result.toString();
}

From source file:com.adobe.acs.commons.util.datadefinitions.impl.TitleAndNodeNameDefinitionBuilderImpl.java

@Override
public final ResourceDefinition convert(String data) {
    data = StringUtils.stripToEmpty(data);

    String name;//w w  w .j a v a  2  s.  c  o m

    final Matcher matcher = PATTERN.matcher(data);

    if (matcher.find() && matcher.groupCount() == 1) {
        name = matcher.group(1);
        name = StringUtils.stripToEmpty(name);
    } else {
        return null;
    }

    String title = PATTERN.matcher(data).replaceAll("");
    title = StringUtils.stripToEmpty(title);

    final BasicResourceDefinition dataDefinition = new BasicResourceDefinition(name);
    dataDefinition.setTitle(title);

    return dataDefinition;
}

From source file:edu.harvard.i2b2.crc.dao.setfinder.querybuilder.temporal.TemporalQuerySimpleSqlParser.java

private String runRegExExpression(String sqlString, String regEx) {
    Pattern p = Pattern.compile(regEx, Pattern.DOTALL | Pattern.CASE_INSENSITIVE);
    Matcher m = p.matcher(sqlString);
    if (m.find() && m.groupCount() > 0)
        return m.group(1).trim();
    else//www  .  j  ava2  s  .  c  o m
        return null;
}

From source file:com.adobe.acs.tools.tag_maker.tagdataconverters.impl.TitleAndNodeNameConverterImpl.java

@Override
public final TagData convert(String data) {
    data = StringUtils.stripToEmpty(data);

    String name;/* w  ww  . j  av a  2s . co  m*/

    final Matcher matcher = PATTERN.matcher(data);

    if (matcher.find() && matcher.groupCount() == 1) {
        name = matcher.group(1);
        name = StringUtils.stripToEmpty(name);
    } else {
        return TagData.EMPTY;
    }

    String title = PATTERN.matcher(data).replaceAll("");
    title = StringUtils.stripToEmpty(title);

    final TagData tagData = new TagData(name);
    tagData.setTitle(title);

    return tagData;
}

From source file:com.rptools.io.TableFileParser.java

private int getEntryWeight(Matcher matcher) {
    if (matcher.groupCount() < 2 || matcher.group(2) == null) {
        return 1;
    }/*from ww  w .  j a  v  a  2  s . com*/
    return parseInt(matcher, 2) - parseInt(matcher, 1) + 1;
}