Example usage for java.util.regex Matcher lookingAt

List of usage examples for java.util.regex Matcher lookingAt

Introduction

In this page you can find the example usage for java.util.regex Matcher lookingAt.

Prototype

public boolean lookingAt() 

Source Link

Document

Attempts to match the input sequence, starting at the beginning of the region, against the pattern.

Usage

From source file:org.onosproject.drivers.juniper.JuniperUtils.java

/**
 * Parses device configuration and returns the device description.
 *
 * @param deviceId    the id of the device
 * @param sysInfoCfg  system configuration
 * @param chassisText chassis string//w  ww .j a v a2 s . c  om
 * @return device description
 */
public static DeviceDescription parseJuniperDescription(DeviceId deviceId, HierarchicalConfiguration sysInfoCfg,
        String chassisText) {
    HierarchicalConfiguration info = sysInfoCfg.configurationAt(SYS_INFO);

    String hw = info.getString(HW_MODEL) == null ? UNKNOWN : info.getString(HW_MODEL);
    String sw = UNKNOWN;
    if (info.getString(OS_NAME) != null || info.getString(OS_VER) != null) {
        sw = info.getString(OS_NAME) + " " + info.getString(OS_VER);
    }
    String serial = info.getString(SER_NUM) == null ? UNKNOWN : info.getString(SER_NUM);

    Matcher matcher = ADD_PATTERN.matcher(chassisText);
    if (matcher.lookingAt()) {
        String chassis = matcher.group(1);
        MacAddress chassisMac = MacAddress.valueOf(chassis);
        return new DefaultDeviceDescription(deviceId.uri(), ROUTER, JUNIPER, hw, sw, serial,
                new ChassisId(chassisMac.toLong()), DefaultAnnotations.EMPTY);
    }
    return new DefaultDeviceDescription(deviceId.uri(), ROUTER, JUNIPER, hw, sw, serial, null,
            DefaultAnnotations.EMPTY);
}

From source file:org.osframework.util.DateUtil.java

/**
 * Determine if the given string is a valid date representation. A valid
 * date conforms to this policy://from   ww w .j  a  v a2 s  . c  om
 * <ul>
 *    <li>All integer parts (year, month, day) are positive values</li>
 *    <li>Year value is greater than or equal to 1583 (first full Gregorian year)</li>
 *    <li>Month value is in range [1,12] inclusive</li>
 *    <li>Day value is in range [1,31] inclusive</li>
 *    <li>Day value does not exceed the maximum value for the month</li>
 * </ul>
 * 
 * @param s string to be examined
 * @return <code>true</code> if string represents a date,
 *         <code>false</code> otherwise
 */
public static boolean isDate(String s) {
    if (StringUtils.isBlank(s))
        return false;
    String trimmed = s.trim();
    int idx = findArrayIndex(trimmed);
    boolean valid = (-1 != idx);
    // 2. Do values fall within accepted ranges?
    if (valid) {
        Pattern p = PATTERN_ARRAY[idx];
        Matcher m = p.matcher(trimmed);
        valid = m.lookingAt();
        if (valid) {
            int year, month, day;
            switch (idx) {
            case DATE_ISO8601:
            case DATE_US_REVERSE:
                year = Integer.parseInt(m.group(1));
                month = Integer.parseInt(m.group(2));
                day = Integer.parseInt(m.group(3));
                break;
            case DATE_US:
                year = Integer.parseInt(m.group(3));
                month = Integer.parseInt(m.group(1));
                day = Integer.parseInt(m.group(2));
                break;
            default:
                year = month = day = -1;
                break;
            }
            valid = ((1583 <= year) && (1 <= month && month <= 12) && (1 <= day
                    && day <= (new DateTime(year, month, 14, 12, 0, 0, 0)).dayOfMonth().getMaximumValue()));
        }
    }
    return valid;
}

From source file:org.phenotips.data.internal.PhenoTipsFeature.java

/**
 * Constructor that copies the data from an XProperty value.
 *
 * @param doc the XDocument representing the described patient in XWiki
 * @param property the feature category XProperty
 * @param value the specific value from the property represented by this object
 *///from   w  w  w .j a v a 2 s.  com
public PhenoTipsFeature(XWikiDocument doc, ListProperty property, String value) {
    super(value);
    this.propertyName = property.getName();
    Matcher nameMatch = NEGATIVE_PREFIX.matcher(this.propertyName);
    this.present = !nameMatch.lookingAt();
    this.type = nameMatch.replaceFirst("");

    this.metadata = new TreeMap<>();
    String metadataNotes = "";
    try {
        BaseObject metadataObject = findMetadataObject(doc);
        if (metadataObject != null) {
            for (FeatureMetadatum.Type metadataType : FeatureMetadatum.Type.values()) {
                StringProperty metadataProp = (StringProperty) metadataObject.get(metadataType.toString());
                if (metadataProp != null && StringUtils.isNotBlank(metadataProp.getValue())) {
                    this.metadata.put(metadataType.toString(), new PhenoTipsFeatureMetadatum(metadataProp));
                }
            }
            metadataNotes = metadataObject.getLargeStringValue("comments");
        }
    } catch (XWikiException ex) {
        // Cannot access metadata, simply ignore
        this.logger.info("Failed to retrieve phenotype metadata: {}", ex.getMessage());
    }
    this.notes = StringUtils.defaultIfBlank(metadataNotes, "");
    // Readonly from now on
    this.metadata = Collections.unmodifiableMap(this.metadata);

    List<String> categoriesList = Collections.emptyList();
    try {
        BaseObject categoriesObject = findCategoriesObject(doc);
        if (categoriesObject != null && categoriesObject.getListValue(META_PROPERTY_CATEGORIES) != null) {
            @SuppressWarnings("unchecked")
            List<String> originalCategories = categoriesObject.getListValue(META_PROPERTY_CATEGORIES);
            categoriesList = Collections.unmodifiableList(originalCategories);
        }
    } catch (XWikiException ex) {
        // Cannot access metadata, simply ignore
        this.logger.info("Failed to retrieve phenotype categories: {}", ex.getMessage());
    }
    this.categories = categoriesList;
}

From source file:org.soaplab.tools.Substitutor.java

/******************************************************************************
 * getTokenValue()/*ww  w . j a  va  2  s. c o m*/
 ******************************************************************************/
private Token getTokenValue(int pos) {
    if (template.charAt(pos) != '$')
        return null;
    String substr = template.substring(pos);
    String tokenId;
    String matched;
    Matcher matcher;

    matcher = re_value1.matcher(substr);
    if (matcher.lookingAt()) {
        matched = matcher.group();
        tokenId = matched.substring(1);
        return new Token(matched.length(), tokenId, false, getValues(tokenId));
    }

    matcher = re_quotedValue1.matcher(substr);
    if (matcher.lookingAt()) {
        matched = matcher.group();
        tokenId = matched.substring(2, matched.length() - 1);
        return new Token(matched.length(), tokenId, true, getValues(tokenId));
    }

    matcher = re_value2.matcher(substr);
    if (matcher.lookingAt()) {
        matched = matcher.group();
        tokenId = matched.substring(2, matched.length() - 1);
        return new Token(matched.length(), tokenId, false, getValues(tokenId));
    }

    matcher = re_quotedValue2.matcher(substr);
    if (matcher.lookingAt()) {
        matched = matcher.group();
        tokenId = matched.substring(3, matched.length() - 2);
        return new Token(matched.length(), tokenId, true, getValues(tokenId));
    }
    return null;
}

From source file:org.soaplab.tools.Substitutor.java

private Token getFunction(int pos) {
    if (template.charAt(pos) != 'f')
        return null; // optimalisation

    String substr = template.substring(pos);
    String matched;// w w  w  .jav a  2s. com
    Matcher matcher;

    matcher = re_foreach.matcher(substr);
    if (matcher.lookingAt()) {
        matched = matcher.group();
        return callFunction(FOREACH, pos, pos + matched.length(), 2);
    }

    matcher = re_foreachs.matcher(substr);
    if (matcher.lookingAt()) {
        matched = matcher.group();
        return callFunction(FOREACHS, pos, pos + matched.length(), 3);
    }

    matcher = re_foreachsq.matcher(substr);
    if (matcher.lookingAt()) {
        matched = matcher.group();
        return callFunction(FOREACHSQ, pos, pos + matched.length(), 3);
    }

    return null;
}

From source file:org.soaplab.tools.Substitutor.java

/******************************************************************************
 * getTokenName()//from  w  w w .ja  v a2 s .co m
 *   (Note that field 'replaceBy' is not used in the returned token.)
 ******************************************************************************/
private Token getTokenName(int pos) {
    if (template.charAt(pos) != '&')
        return null;
    String substr = template.substring(pos);
    String matched;
    Matcher matcher;

    matcher = re_qualifier1.matcher(substr);
    if (matcher.lookingAt()) {
        matched = matcher.group();
        return new Token(matched.length(), matched.substring(1), true, null);
    }

    matcher = re_qualifier2.matcher(substr);
    if (matcher.lookingAt()) {
        matched = matcher.group();
        return new Token(matched.length(), matched.substring(2, matched.length() - 1), true, null);
    }

    return null;
}

From source file:org.sqlite.date.FastDateParser.java

/**
 * Initialize derived fields from defining fields.
 * This is called from constructor and from readObject (de-serialization)
 *
 * @param definingCalendar the {@link java.util.Calendar} instance used to initialize this FastDateParser
 *///from  w  ww  .  ja va2  s . c o m
private void init(final Calendar definingCalendar) {

    final StringBuilder regex = new StringBuilder();
    final List<Strategy> collector = new ArrayList<Strategy>();

    final Matcher patternMatcher = formatPattern.matcher(pattern);
    if (!patternMatcher.lookingAt()) {
        throw new IllegalArgumentException(
                "Illegal pattern character '" + pattern.charAt(patternMatcher.regionStart()) + "'");
    }

    currentFormatField = patternMatcher.group();
    Strategy currentStrategy = getStrategy(currentFormatField, definingCalendar);
    for (;;) {
        patternMatcher.region(patternMatcher.end(), patternMatcher.regionEnd());
        if (!patternMatcher.lookingAt()) {
            nextStrategy = null;
            break;
        }
        final String nextFormatField = patternMatcher.group();
        nextStrategy = getStrategy(nextFormatField, definingCalendar);
        if (currentStrategy.addRegex(this, regex)) {
            collector.add(currentStrategy);
        }
        currentFormatField = nextFormatField;
        currentStrategy = nextStrategy;
    }
    if (patternMatcher.regionStart() != patternMatcher.regionEnd()) {
        throw new IllegalArgumentException(
                "Failed to parse \"" + pattern + "\" ; gave up at index " + patternMatcher.regionStart());
    }
    if (currentStrategy.addRegex(this, regex)) {
        collector.add(currentStrategy);
    }
    currentFormatField = null;
    strategies = collector.toArray(new Strategy[collector.size()]);
    parsePattern = Pattern.compile(regex.toString());
}

From source file:org.sqlite.date.FastDateParser.java

/**
 * This implementation updates the ParsePosition if the parse succeeeds.
 * However, unlike the method {@link java.text.SimpleDateFormat#parse(String, ParsePosition)}
 * it is not able to set the error Index - i.e. {@link ParsePosition#getErrorIndex()} -  if the parse fails.
 * <p>//  ww  w . j  av  a 2s . c om
 * To determine if the parse has succeeded, the caller must check if the current parse position
 * given by {@link ParsePosition#getIndex()} has been updated. If the input buffer has been fully
 * parsed, then the index will point to just after the end of the input buffer.
 *
 * @see org.apache.commons.lang3.time.DateParser#parse(java.lang.String, java.text.ParsePosition)
 * {@inheritDoc}
 */
public Date parse(final String source, final ParsePosition pos) {
    final int offset = pos.getIndex();
    final Matcher matcher = parsePattern.matcher(source.substring(offset));
    if (!matcher.lookingAt()) {
        return null;
    }
    // timing tests indicate getting new instance is 19% faster than cloning
    final Calendar cal = Calendar.getInstance(timeZone, locale);
    cal.clear();

    for (int i = 0; i < strategies.length;) {
        final Strategy strategy = strategies[i++];
        strategy.setCalendar(this, cal, matcher.group(i));
    }
    pos.setIndex(offset + matcher.end());
    return cal.getTime();
}

From source file:org.xchain.framework.util.AttributesUtil.java

/**
 * Parses an attribute value template into fixed and dynamic parts.  This list will always start with a fixed part and
 * then include alternating dynamic and fixed parts.
 *///from   w  w  w  .  ja  v a2s  . com
public static List<String> parseAttributeValueTemplate(String attributeValueTemplate) throws SAXException {
    // the result.
    ArrayList<String> result = new ArrayList<String>();

    // create the matcher.
    Matcher matcher = attributeValueTemplatePattern.matcher(attributeValueTemplate);

    while (matcher.lookingAt()) {
        String fixedPart = matcher.group(1);
        String dynamicPart = matcher.group(2);

        if (result.isEmpty() && fixedPart == null) {
            result.add("");
        }

        if (fixedPart != null) {
            result.add(fixedPart.replaceAll("\\{\\{", "{").replaceAll("\\}\\}", "}"));
        }
        if (dynamicPart != null) {
            result.add(dynamicPart);
        }
        matcher.region(matcher.regionStart() + matcher.group().length(), matcher.regionEnd());
    }

    if (!matcher.hitEnd()) {
        throw new SAXException(
                "The attribute value template '" + attributeValueTemplate + "' has an error between characters "
                        + matcher.regionStart() + " and " + matcher.regionEnd() + ".");
    }

    return result;
}

From source file:org.xwiki.rendering.internal.parser.xhtml.wikimodel.XHTMLXWikiGeneratorListener.java

/**
 * Recognize the passed reference and figure out what type of link it should be:
 * <ul>//from  w w  w  . j a v a2s  .  c  o m
 *   <li>UC1: the reference points to a valid URL, we return a reference of type "url",
 *       e.g. {@code http://server/path/reference#anchor}</li>
 *   <li>UC2: the reference is not a valid URL, we return a reference of type "path",
 *       e.g. {@code path/reference#anchor}</li>
 * </ul>
 *
 * @param rawReference the full reference (e.g. "/some/path/something#other")
 * @return the properly typed {@link ResourceReference} matching the use cases
 */
private ResourceReference computeResourceReference(String rawReference) {
    ResourceReference reference;

    // Do we have a valid URL?
    Matcher matcher = URL_SCHEME_PATTERN.matcher(rawReference);
    if (matcher.lookingAt()) {
        // We have UC1
        reference = new ResourceReference(rawReference, ResourceType.URL);
    } else {
        // We have UC2
        reference = new ResourceReference(rawReference, ResourceType.PATH);
    }

    return reference;
}