List of usage examples for java.util.regex Matcher groupCount
public int groupCount()
From source file:org.cleverbus.api.entity.Request.java
/** * Gets normalized endpoint/target URI./*from w w w . jav a2 s . c o m*/ * * @return URI */ public String getNormalizedUri() { Matcher uriMatcher = NORMALIZED_URI_PATTERN.matcher(this.uri); if (uriMatcher.matches() && uriMatcher.groupCount() > 0) { return uriMatcher.group(1); } return this.uri; }
From source file:com.genericworkflownodes.knime.nodegeneration.templates.feature.FeatureXMLTemplate.java
private Matcher matchVersion(final String version) { Matcher m = VERSION_PATTERN.matcher(version); // via definition this has to be true boolean found = m.find(); assert found : "Version should be compliant to the pattern ^(\\d+)(\\.\\d+)?(\\.\\d+)?(.[a-zA-Z0-9-_]+)?$"; assert m.groupCount() == 4 : "Something went wrong when matching the version."; return m;//from ww w . ja v a2 s . c om }
From source file:com.streamsets.pipeline.stage.processor.fieldmask.FieldMaskProcessor.java
@VisibleForTesting String regExMask(Field field, FieldMaskConfig fieldMaskConfig) { String value = field.getValueAsString(); Matcher matcher = regExToPatternMap.get(fieldMaskConfig.regex).matcher(value); if (matcher.matches()) { int groupCount = matcher.groupCount(); //create a masked string of the same length as the original string StringBuilder resultString = new StringBuilder(); for (int i = 0; i < value.length(); i++) { resultString.append(MASK_CHAR); }/*from www. j a v a2s.co m*/ //for each group that needs to be shown, replace the masked string with the original string characters at those //positions Set<Integer> groupsToShow = regexToGroupsToShowMap.get(fieldMaskConfig.regex); if (groupsToShow != null && !groupsToShow.isEmpty()) { for (int i = 1; i <= groupCount; i++) { if (groupsToShow.contains(i)) { resultString.replace(matcher.start(i), matcher.end(i), matcher.group(i)); } } } return resultString.toString(); } return field.getValueAsString(); }
From source file:edu.cornell.mannlib.vitro.webapp.controller.individual.IndividualRequestAnalyzer.java
private String checkForRedirect() { // A "format" parameter is special, and is dealt with elsewhere. String formatParam = getRequestParameter("format", ""); if (!formatParam.isEmpty()) { return null; }/* w w w. j av a 2 s. co m*/ // Is it "/individual/" followed by a single group? Matcher m = URI_PATTERN.matcher(url); if (!m.matches() || m.groupCount() < 1) { return null; } // Then, use the "accept" header to decide how to redirect it. ContentType c = checkAcceptHeaderForLinkedDataRequest(); if (c != null) { String mediaType = c.getMediaType(); if (RDFXML_MIMETYPE.equals(mediaType)) { return "/individual/" + m.group(1) + "/" + m.group(1) + ".rdf"; } else if (N3_MIMETYPE.equals(mediaType)) { return "/individual/" + m.group(1) + "/" + m.group(1) + ".n3"; } else if (TTL_MIMETYPE.equals(mediaType)) { return "/individual/" + m.group(1) + "/" + m.group(1) + ".ttl"; } else if (JSON_MIMETYPE.equals(mediaType) || JSON_LD_MIMETYPE.equals(mediaType)) { return "/individual/" + m.group(1) + "/" + m.group(1) + ".jsonld"; } } // or redirect to the canonical URL for HTML representation. return "/display/" + m.group(1); }
From source file:net.sourceforge.pmd.lang.java.rule.bestpractices.AvoidUsingHardCodedIPRule.java
protected boolean isIPv4(final char firstChar, final String s) { // Quick check before using Regular Expression // 1) At least 7 characters // 2) 1st character must be a digit from '0' - '9' // 3) Must contain at least 1 . (period) if (s.length() < 7 || !isLatinDigit(firstChar) || s.indexOf('.') < 0) { return false; }/* w w w .j a v a 2s . co m*/ Matcher matcher = IPV4_PATTERN.matcher(s); if (matcher.matches()) { // All octets in range [0, 255] for (int i = 1; i <= matcher.groupCount(); i++) { int octet = Integer.parseInt(matcher.group(i)); if (octet < 0 || octet > 255) { return false; } } return true; } else { return false; } }
From source file:com.clustercontrol.hub.util.CollectStringDataParser.java
/** * ????????????/*from w w w. ja va2 s. co m*/ * * @param data * @return */ public CollectStringData parse(CollectStringData data) { Map<String, CollectDataTag> tagMap = new HashMap<>(); for (CollectDataTag tag : data.getTagList()) { tagMap.put(tag.getKey(), tag); } if (isNullOrZeroLength(format.getTimestampRegex()) && isNullOrZeroLength(format.getTimestampFormat())) { // do nothing, use currentTimeMillis as timestamp } else { Matcher m = timestampPattern.matcher(data.getValue()); if (m.find() && m.groupCount() > 0) { String timestampStr = m.group(1); try { DateTime datetime = timestampFormatter.parseDateTime(timestampStr); if (datetime.year().get() == 0) { // for messages without year, like syslog DateTime now = new DateTime(); DateTimeFormatter timestampFormatterWithCurrentYear = timestampFormatter .withDefaultYear(now.year().get()); DateTimeFormatter timestampFormatterWithLastYear = timestampFormatter .withDefaultYear(now.year().get() - 1); datetime = timestampFormatterWithCurrentYear.parseDateTime(timestampStr); if (datetime.getMillis() - now.getMillis() > 1000 * 60 * 60 * 24 * 7) { // treat messages as end of year (threshold : 1 week) datetime = timestampFormatterWithLastYear.parseDateTime(timestampStr); } } tagMap.put(KEY_TIMESTAMP_IN_LOG, new CollectDataTag( new CollectDataTagPK(data.getCollectId(), data.getDataId(), KEY_TIMESTAMP_IN_LOG), ValueType.number, Long.toString(datetime.getMillis()))); } catch (IllegalArgumentException e) { log.warn(String.format("invalid timestamp string : format = %s, string = %s", format.getTimestampRegex(), timestampStr)); } } } for (LogFormatKey keyword : format.getKeyPatternList()) { Pattern p = keywordPatternMap.get(keyword.getKey()); if (null == p) { log.debug(String.format("Pattern is null keyword : pattern=%s", keyword.getPattern())); continue; } Matcher m = p.matcher(data.getValue()); String matchedStr = null; switch (keyword.getKeyType()) { case parsing: if (m.find() && m.groupCount() > 0) { matchedStr = m.group(1); } break; case fixed: if (m.find()) { matchedStr = keyword.getValue(); } break; } if (matchedStr != null && keyword.getValueType() == ValueType.string) { tagMap.put(keyword.getKey(), new CollectDataTag( new CollectDataTagPK(data.getCollectId(), data.getDataId(), keyword.getKey()), keyword.getValueType(), matchedStr)); } else if (matchedStr != null && keyword.getValueType() != ValueType.string) { tagMap.put(keyword.getKey(), new CollectDataTag( new CollectDataTagPK(data.getCollectId(), data.getDataId(), keyword.getKey()), keyword.getValueType(), matchedStr)); switch (keyword.getValueType()) { case number: try { new BigDecimal(matchedStr); } catch (NumberFormatException e) { log.warn(String.format("not match number format : value=%s, source=%s, pattern=%s", matchedStr, data.getValue(), p.pattern())); } break; case bool: if (!"true".equalsIgnoreCase(matchedStr) || !"false".equalsIgnoreCase(matchedStr)) { log.warn(String.format("not match boolean type : value=%s, source=%s, pattern=%s", matchedStr, data.getValue(), p.pattern())); } break; default: log.warn(String.format("unexpected value type : type=%s, value=source=%s, pattern=%s", keyword.getValueType().name(), data.getValue(), p.pattern())); break; } } } data.setTagList(new ArrayList<>(tagMap.values())); return data; }
From source file:com.norconex.commons.lang.io.TextReader.java
/** * Reads the next chunk of text, up to the maximum read size specified. * It tries as much as possible to break long text into paragraph, * sentences or words, before returning. See class documentation. * @return text read// w w w . j a v a 2 s. c o m * @throws IOException problem reading text. */ public String readText() throws IOException { char[] text = new char[maxReadSize - buffer.length()]; int num = reader.read(text); if (num == -1) { return null; } buffer.append(String.valueOf(text, 0, num)); // Return all if we reached the end. reader.mark(1); if (reader.read() == -1) { String t = buffer.toString(); buffer.setLength(0); reader.reset(); return t; } else { reader.reset(); } Matcher m = null; // Try breaking at paragraph: m = paragraphDelimiterPattern.matcher(buffer); if (m.find()) { int mStart = m.start(m.groupCount()); int mEnd = m.end(m.groupCount()); int substringEnd = mEnd; if (removeTrailingDelimiter) { substringEnd = mStart; } String t = buffer.substring(0, substringEnd); buffer.delete(0, substringEnd); return t; } // Try breaking at sentence: m = sentencePattern.matcher(buffer); if (m.find()) { int mStart = m.start(1); int mEnd = m.end(1); int substringEnd = mEnd; if (removeTrailingDelimiter) { substringEnd = mStart; } String t = buffer.substring(0, substringEnd); buffer.delete(0, substringEnd); return t; } // Try breaking at word: m = wordDelimiterPattern.matcher(buffer); if (m.find()) { int mStart = m.start(m.groupCount()); int mEnd = m.end(m.groupCount()); int substringEnd = mEnd; if (removeTrailingDelimiter) { substringEnd = mStart; } String t = buffer.substring(0, substringEnd); buffer.delete(0, substringEnd); return t; } String t = buffer.toString(); buffer.setLength(0); return t; }
From source file:org.codice.ddf.security.idp.client.IdpMetadataTest.java
/** * Return a modified version of the (XML) input. The cache duration and valid-until time are * modified to match the respective input parameters. If null is passed for the cache duration, * the value of the cache duration already in the XML is used. Because of how the substitution * works, this method can only be called only once per test. Otherwise, it will create multiple * "validUntil" XML attributes./*from ww w .j a va 2 s.c o m*/ * * @param validUntil the validUntil instant * @param xml the SAML entity description document * @return SAML entity description document with a validUntil date */ private String setValidUntil(Instant validUntil, String iso8601Duration, String xml) { Pattern pattern = Pattern.compile("cacheDuration=\"(\\w*)\""); Matcher matcher = pattern.matcher(xml); assertThat("Cannot setup test data - precondition not met", matcher.find(), is(true)); assertThat("Cannot setup test data - precondition not met", matcher.groupCount(), is(1)); String duration = iso8601Duration == null ? matcher.group(1) : iso8601Duration; DateTimeFormatter formatter = DateTimeFormatter.ISO_OFFSET_DATE_TIME; ZonedDateTime temporalAccessor = ZonedDateTime.ofInstant(validUntil, ZoneId.systemDefault()); String isoTimestamp = formatter.format(temporalAccessor); return xml.replaceFirst(CACHE_DURATION_REGEX, String.format("cacheDuration=\"%s\" validUntil=\"%s\"", duration, isoTimestamp)); }
From source file:org.apache.nifi.processors.standard.HashAttribute.java
private SortedMap<String, String> getRelevantAttributes(final FlowFile flowFile, final Map<String, Pattern> patterns) { final SortedMap<String, String> attributeMap = new TreeMap<>(); for (final Map.Entry<String, Pattern> entry : patterns.entrySet()) { final String attributeName = entry.getKey(); final String attributeValue = flowFile.getAttribute(attributeName); if (attributeValue != null) { final Pattern pattern = entry.getValue(); if (pattern == null) { attributeMap.put(attributeName, attributeValue); } else { final Matcher matcher = pattern.matcher(attributeValue); if (matcher.matches()) { if (matcher.groupCount() == 0) { attributeMap.put(attributeName, matcher.group(0)); } else { attributeMap.put(attributeName, matcher.group(1)); }/*from ww w . ja va 2 s . c o m*/ } } } } return attributeMap; }
From source file:org.apache.struts2.util.RegexPatternMatcher.java
public boolean match(Map<String, String> map, String data, RegexPatternMatcherExpression expr) { Matcher matcher = expr.getPattern().matcher(data); Map<Integer, String> params = expr.getParams(); if (matcher.matches()) { map.put("0", data); //extract values and get param names from the expression for (int i = 1; i <= matcher.groupCount(); i++) { String paramName = params.get(i); String value = matcher.group(i); //by name map.put(paramName, value);//ww w . j a v a 2s . c o m //by index so the old {1} still works map.put(String.valueOf(i), value); } return true; } else { return false; } }