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.vionto.vithesaurus.wikipedia.CommonsAudioDumper.java

License getLicenseOrNull(String title, String text) {
    String licenseUrl = null;/*from   www . ja  va2 s  .  c om*/
    String attribution = null;
    for (LicensePattern licensePattern : LICENSE_PATTERNS) {
        Matcher pattern = licensePattern.pattern.matcher(text);
        if (pattern.find()) {
            if (pattern.groupCount() >= 1) {
                licenseUrl = licensePattern.licenseUrl.replace("$1", pattern.group(1));
            } else {
                licenseUrl = licensePattern.licenseUrl;
            }
            if (pattern.groupCount() >= 2) {
                // TODO: find more ways to extract attribution, this one is rarely used
                attribution = pattern.group(2);
            }
        }
    }
    if (licenseUrl == null) {
        System.err.println("No license found for: " + title);
        return null;
    } else {
        return new License(licenseUrl, attribution);
    }
}

From source file:net.solarnetwork.node.util.TemplatedMessageSource.java

@Override
public String getMessage(final MessageSourceResolvable resolvable, Locale locale)
        throws NoSuchMessageException {
    final String[] codes = resolvable.getCodes();
    if (pat != null) {
        for (int i = 0; i < codes.length; i++) {
            Matcher m = pat.matcher(codes[i]);
            final int count = m.groupCount();
            if (m.matches() && count > 0) {
                // remap using regex capture group
                StringBuilder buf = new StringBuilder();
                for (int j = 1; j <= count; j++) {
                    buf.append(m.group(j));
                }//w  ww  .  jav  a  2 s . com
                codes[i] = buf.toString();
            }
        }
    }
    return delegate.getMessage(new MessageSourceResolvable() {

        @Override
        public String getDefaultMessage() {
            return resolvable.getDefaultMessage();
        }

        @Override
        public String[] getCodes() {
            return codes;
        }

        @Override
        public Object[] getArguments() {
            return resolvable.getArguments();
        }
    }, locale);
}

From source file:org.springframework.core.util.AntPathStringMatcher.java

/**
 * Main entry point./*from   ww  w .  j  a v  a 2s . c  o  m*/
 *
 * @return <code>true</code> if the string matches against the pattern, or <code>false</code> otherwise.
 */
public boolean matchStrings() {
    Matcher matcher = pattern.matcher(str);
    if (matcher.matches()) {
        if (uriTemplateVariables != null) {
            for (int i = 1; i <= matcher.groupCount(); i++) {
                String name = this.variableNames.get(i - 1);
                String value = matcher.group(i);
                uriTemplateVariables.put(name, value);
            }
        }
        return true;
    } else {
        return false;
    }
}

From source file:org.candlepin.common.exceptions.mappers.BadRequestExceptionMapper.java

private String extractIllegalValue(String msg) {
    Matcher paramMatcher = PARAM_REGEX.matcher(msg);
    Matcher illegalValMatcher = ILLEGAL_VAL_REGEX.matcher(msg);
    if (paramMatcher.find() && illegalValMatcher.find()) {
        if ((paramMatcher.groupCount() & illegalValMatcher.groupCount()) == 2) {
            return i18n.get().tr("{0} is not a valid value for {1}", illegalValMatcher.group(1),
                    paramMatcher.group(1));
        }/*  w  ww. j a  v  a 2 s .c o  m*/
    }
    return i18n.get().tr("Bad Request");
}

From source file:com.healthcit.cacure.web.controller.XFormPreviewController.java

@SuppressWarnings("unchecked")
@RequestMapping(value = Constants.XFORM_PREVIEW_URI, method = RequestMethod.GET)
public ModelAndView showXForm(@RequestParam(value = "file", required = false) String fileName,
        @RequestParam(value = Constants.FORM_ID, required = false) Long formID) {
    ModelAndView mav = new ModelAndView();
    mav.setViewName(XFORM_PREVIEW_VIEW);
    Map model = mav.getModel();/*from   w w w .java 2 s.  co  m*/
    String xformModel = "";
    String xformBody = "";

    // if file present - read in file
    String xFormData;
    if (StringUtils.hasText(fileName))
        xFormData = readResource(fileName);
    else
        xFormData = loadFormDB(formID);

    if (xFormData != null) {
        // split XForm into model and body
        int startOfModelIdx = xFormData.indexOf(MODEL_START_TAG);
        int endOfModelIdx = xFormData.lastIndexOf(MODEL_END_TAG);
        int startOfBodylIdx = xFormData.indexOf(BODY_START_TAG);
        int endOfBodyIdx = xFormData.indexOf(BODY_END_TAG);
        if (startOfModelIdx >= 0 && endOfModelIdx > 0) {
            endOfModelIdx += MODEL_END_TAG.length();
            xformModel = xFormData.substring(startOfModelIdx, endOfModelIdx);
            // xformModel = xformModel.replaceAll("xmlns=\"http://www.healthcit.com/FormDataModel\"", "xmlns=\"\"");
            // find form Title
            Pattern p = Pattern.compile("(<form.*)(.*name=\"(.*?)\" .*>)");
            Matcher m = p.matcher(xformModel);
            if (m.find() && m.groupCount() > 0) {
                String formTitle = m.group(3);
                model.put(XFORM_TITLE, formTitle);
            } else {
                model.put(XFORM_TITLE, "Unknown Form");
            }
            model.put(XFORM_MODEL, xformModel);

        }
        if (startOfBodylIdx >= 0 && endOfBodyIdx > 0) {
            startOfBodylIdx += BODY_START_TAG.length();
            xformBody = xFormData.substring(startOfBodylIdx, endOfBodyIdx);
            // Remove/disable the custom JS script that produces the "Confirm Leave Page" warning
            // Confirm Leave Page warning is disabled in xforms-layout.jsp

            //            xformBody = xformBody.replaceAll( "xforms_html.js", "xforms_htl2.js" );

            model.put(XFORM_BODY, xformBody);
        }

    } else
        model.put(XFORM_BODY, "Unable to load XForm");

    return mav;

}

From source file:de.tudarmstadt.ukp.dkpro.core.textnormalizer.transformation.HyphenationRemover.java

@Override
public void process(JCas aInput, JCas aOutput) throws AnalysisEngineProcessException {
    StringBuilder c_new = new StringBuilder();
    final Matcher m = HYPHEN_PATTERN.matcher(aInput.getDocumentText());
    while (m.find()) {
        // The capturing groups count should be exactly 2.
        assert m.groupCount() == 2 : "Expected 2 groups but got " + m.groupCount();

        c_new.setLength(0);
        c_new.append(m.group(1));
        c_new.append(m.group(2));

        if (dict.contains(c_new.toString())) {
            replace(m.start(1), m.end(2), c_new.toString());
            //                getLogger().info(
            //                        "Conflated: [" + aInput.getDocumentText().substring(m.start(1), m.end(2))
            //                                + "] to [" + c_new + "]");
        }/*from w ww  .j a va 2 s. c  om*/
    }
}

From source file:com.nextdoor.bender.deserializer.regex.RegexDeserializer.java

@Override
public DeserializedEvent deserialize(String raw) {
    Matcher m = this.pattern.matcher(raw);

    if (!m.matches()) {
        throw new DeserializationException("raw event does not match string");
    }/* www  .j a  v a  2s  .  c  om*/

    int groups = m.groupCount();

    JsonObject obj = new JsonObject();
    for (int i = 0; i < groups && i < fields.size(); i++) {
        String str = m.group(i + 1);
        ReFieldConfig field = this.fields.get(i);

        switch (field.getType()) {
        case BOOLEAN:
            obj.addProperty(field.getName(), Boolean.parseBoolean(str));
            break;
        case NUMBER:
            obj.addProperty(field.getName(), NumberUtils.createNumber(str));
            break;
        case STRING:
            obj.addProperty(field.getName(), str);
            break;
        default:
            obj.addProperty(field.getName(), str);
            break;
        }
    }

    return new GenericJsonEvent(obj);
}

From source file:com.adaptris.core.http.jetty.JettyRouteSpec.java

private Set<MetadataElement> createMetadata(Matcher matcher) {
    Set<MetadataElement> result = new HashSet<>();
    for (int i = 1; i <= matcher.groupCount(); i++) {
        result.add(new MetadataElement(getMetadataKeys().get(i - 1), matcher.group(i)));
    }/*from www.  j  ava2 s. c om*/
    return result;
}

From source file:org.commoncrawl.mapred.pipelineV3.domainmeta.crawlstats.DNSFailuresCollectorStep.java

@Override
public void map(LongWritable key, Text value, OutputCollector<TextBytes, TextBytes> output, Reporter reporter)
        throws IOException {
    Matcher m = pattern.matcher(value.toString());
    if (m.matches() && m.groupCount() >= 2) {
        String domain = m.group(1);
        String rootDomain = URLUtils.extractRootDomainName(domain);

        if (rootDomain != null) {
            long domainFP = SuperDomainList.domainFingerprintGivenName(rootDomain);
            if (superDomainIdSet.contains(domainFP)) {
                domain = rootDomain;//  w  w w .j a  v a2 s . c  o  m
            }

            JsonObject objectOut = new JsonObject();

            String failureReason = m.group(2);
            if (failureReason.equalsIgnoreCase("NXDOMAIN")) {
                objectOut.addProperty("nxdomain", 1);
            } else if (failureReason.equalsIgnoreCase("SERVFAIL")) {
                objectOut.addProperty("servfail", 1);
            } else if (failureReason.equalsIgnoreCase("NOERROR")) {
                objectOut.addProperty("noerror", 1);
            } else {
                objectOut.addProperty("other", 1);
            }
            output.collect(new TextBytes(domain), new TextBytes(objectOut.toString()));
        }
    }
}

From source file:synapticloop.scaleway.api.response.BasePaginationResponse.java

/**
 * Parse the 'Link' header to determine the current page, and the number of 
 * results returned per page//from w w w . j ava 2  s. co m
 * 
 * @param value The header value to parse
 */
private void parseLinkHeader(String value) {
    // should look something like this:
    // </images?page=1&per_page=50>; rel="first",</images?page=4&per_page=50>; rel="previous",</images?page=5&per_page=50>; rel="last"

    Matcher previousMatcher = PATTERN_PREVIOUS.matcher(value);
    if (previousMatcher.matches() && previousMatcher.groupCount() == 2) {
        this.currentPage = Integer.parseInt(previousMatcher.group(1)) + 1;
        this.numPerPage = Integer.parseInt(previousMatcher.group(2));
        return;
    }

    // should look something like this:
    // </images?page=2&per_page=50>; rel="next",</images?page=5&per_page=50>; rel="last"
    Matcher nextMatcher = PATTERN_NEXT.matcher(value);
    if (nextMatcher.matches() && nextMatcher.groupCount() == 2) {
        this.currentPage = Integer.parseInt(nextMatcher.group(1)) - 1;
        this.numPerPage = Integer.parseInt(nextMatcher.group(2));
        return;
    }

    // at this point - there is only one page and we are on it
    // should look something like this:
    // </servers?page=1&per_page=2>; rel="last"
    Matcher lastMatcher = PATTERN_LAST.matcher(value);
    if (lastMatcher.matches() && lastMatcher.groupCount() == 2) {
        this.currentPage = Integer.parseInt(lastMatcher.group(1));
        this.numPerPage = Integer.parseInt(lastMatcher.group(2));
        return;
    }
}