Example usage for java.util.regex Matcher reset

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

Introduction

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

Prototype

public Matcher reset(CharSequence input) 

Source Link

Document

Resets this matcher with a new input sequence.

Usage

From source file:org.archive.util.TextUtils.java

public static void recycleMatcher(Matcher m) {
    // while cached, eliminate reference to potentially-large prior 'input'
    m.reset("");
    final Map<String, Matcher> matchers = TL_MATCHER_MAP.get();
    matchers.put(m.pattern().pattern(), m);
}

From source file:bin.spider.frame.uri.TextUtils.java

/**
 * Get a matcher object for a precompiled regex pattern.
 * //from   www  .ja  v  a2s .  c  o m
 * This method tries to reuse Matcher objects for efficiency.
 * It can hold for recycling one Matcher per pattern per thread. 
 * 
 * Matchers retrieved should be returned for reuse via the
 * recycleMatcher() method, but no errors will occur if they
 * are not.
 * 
 * This method is a hotspot frequently accessed.
 *
 * @param pattern the string pattern to use
 * @param input the character sequence the matcher should be using
 * @return a matcher object loaded with the submitted character sequence
 */
public static Matcher getMatcher(String pattern, CharSequence input) {
    if (pattern == null) {
        throw new IllegalArgumentException("String 'pattern' must not be null");
    }
    input = new InterruptibleCharSequence(input);
    final Map<String, Matcher> matchers = TL_MATCHER_MAP.get();
    Matcher m = (Matcher) matchers.get(pattern);
    if (m == null) {
        m = Pattern.compile(pattern).matcher(input);
    } else {
        matchers.put(pattern, null);
        m.reset(input);
    }
    return m;
}

From source file:esg.common.Utils.java

/**
   In an attempt to be a bit more efficient.  If there is a lot of
   comparing that needs to be done it is better to pass in
   matchers, rather than have the matchers be instantiated by the
   Pattern every time a comparison is done.  Matchers are not
   thread safe therefore this method is NOT thread safe.  So be
   aware.  If in doubt call the other version of this method.
        /* w w  w.j  a  va 2  s.co m*/
   @param candidate the first version value to compare
   @param c_matcher a Matcher object from a Pattern that knows how to tokenize the version values
   @param reference the second version value to compare
   @param r_matcher a Matcher object from a Pattern that knows how to tokenize the version values
   @throws InvalideVersionStringException runtime exception thrown when a value cannot be numerically parsed.
   @return 1 if candidate > reference; -1 if candidate < reference; 0 if candidate = refernece;
 */
public static int versionCompare(String candidate, Matcher c_matcher, String reference, Matcher r_matcher)
        throws esg.common.InvalidVersionStringException {
    c_matcher.reset(candidate);
    r_matcher.reset(reference);

    int c, r = 0;
    try {
        while (c_matcher.find() && r_matcher.find()) {
            c = Integer.parseInt(c_matcher.group(1));
            r = Integer.parseInt(r_matcher.group(1));

            //log.trace("Comparing "+c+" and "+r);
            if (c > r)
                return 1;
            else if (c < r)
                return -1;
        }

        //When version positions don't line up...
        int c_len = candidate.length();
        int r_len = reference.length();
        //log.trace("candidate length = "+c_len);
        //log.trace("reference length = "+r_len);
        if (c_len > r_len) {
            c_matcher.reset(candidate.substring(r_len));
            while (c_matcher.find()) {
                if (Integer.parseInt(c_matcher.group(1)) > 0) {
                    return 1;
                }
            }
        }
        if (c_len < r_len) {
            r_matcher.reset(reference.substring(c_len));
            while (r_matcher.find()) {
                if (Integer.parseInt(r_matcher.group(1)) > 0) {
                    return -1;
                }
            }
        }
        return 0;
    } catch (NumberFormatException e) {
        log.error("Improper version string! " + e.getMessage());
        throw new InvalidVersionStringException(e);
    } catch (Exception e) {
        log.error("Improper version string! " + e.getMessage());
        throw new InvalidVersionStringException(e);
    }
}

From source file:Grep.java

/**
 * Use the linePattern to break the given CharBuffer into lines, applying the
 * input pattern to each line to see if we have a match
 *///ww w. j  a va 2s .  c o  m
private static List grep() {
    List matches = new ArrayList();
    Matcher lm = linePattern.matcher(indexFile); // Line matcher
    Matcher pm = null; // Pattern matcher
    int lines = 0;
    while (lm.find()) {
        lines++;
        CharSequence cs = lm.group(); // The current line
        if (pm == null)
            pm = pattern.matcher(cs);
        else
            pm.reset(cs);
        if (pm.find()) {
            matches.add(cs.toString());
        }
        if (lm.end() == indexFile.limit())
            break;
    }
    return matches;
}

From source file:org.rhq.enterprise.server.perspective.activator.ActivatorHelper.java

/**
  * Test trait conditions against resources.  Optionally, one or all resources must much all of the
  * trait conditions./*w w w.  j a va 2  s. c om*/
  * 
  * @param subject The current user
  * @param traitMatchers The trait activator pattern matchers that must all be satisfied
  * @param resources The resources whose trait values will be tested
  * @param matchAll If true then all resources must pass, if false only one must pass
  * @return true if, optionally, all or any resources satisfy the trait conditions
  */
public static boolean areTraitsSatisfied(Subject subject, Map<String, Matcher> traitMatchers,
        Collection<Resource> resources, boolean matchAll) {

    // return true if there are no trait activators to satisfy
    if (traitMatchers.isEmpty()) {
        return true;
    }

    MeasurementDataManagerLocal measurementDataManager = LookupUtil.getMeasurementDataManager();

    for (Resource resource : resources) {
        boolean traitsSatisfied = true;
        List<MeasurementDataTrait> traits = measurementDataManager.findCurrentTraitsForResource(subject,
                resource.getId(), null);

        int numTraitsTested = 0;
        for (MeasurementDataTrait trait : traits) {
            Matcher traitMatcher = traitMatchers.get(trait.getName());
            if (null != traitMatcher) {
                ++numTraitsTested;

                traitMatcher.reset(trait.getValue());
                if (!traitMatcher.find()) {
                    traitsSatisfied = false;
                    break;
                }
            }
        }

        if (traitsSatisfied) {
            if (numTraitsTested != traitMatchers.size()) {
                if (LOG.isDebugEnabled()) {
                    String error = "" //
                            + "Potential error in perspective descriptor." //
                            + " Not all trait activators matched trait for resource type: "
                            + traitMatchers.keySet() //
                            + " Or, Trait value may not yet have been collected for resource.";
                    LOG.debug(error);
                }

                return false;
            }

            if (!matchAll) {
                return true;
            }
        } else {
            if (matchAll) {
                return false;
            }
        }
    }

    // if we've run through all the resources then either every resource matched (for matchAll) or
    // every resource failed (for !matchAll)
    return matchAll;
}

From source file:org.archive.util.TextUtils.java

/**
 * Get a matcher object for a precompiled regex pattern.
 * /* ww  w.  jav  a2  s .  co m*/
 * This method tries to reuse Matcher objects for efficiency.
 * It can hold for recycling one Matcher per pattern per thread. 
 * 
 * Matchers retrieved should be returned for reuse via the
 * recycleMatcher() method, but no errors will occur if they
 * are not.
 * 
 * This method is a hotspot frequently accessed.
 *
 * @param pattern the string pattern to use
 * @param input the character sequence the matcher should be using
 * @return a matcher object loaded with the submitted character sequence
 */
public static Matcher getMatcher(String pattern, CharSequence input) {
    if (pattern == null) {
        throw new IllegalArgumentException("String 'pattern' must not be null");
    }
    input = new InterruptibleCharSequence(input);
    final Map<String, Matcher> matchers = TL_MATCHER_MAP.get();
    Matcher m = (Matcher) matchers.get(pattern);
    if (m == null) {
        m = PATTERNS.getUnchecked(pattern).matcher(input);
    } else {
        matchers.put(pattern, null);
        m.reset(input);
    }
    return m;
}

From source file:de.escidoc.sb.gsearch.xslt.EscidocCoreAccessor.java

/**
 * Calls resource for given rest-uri to get object-xml. 
 * Parses values of elements or attributes given with
 * elementPath, attributeName and attributeNamespaceUri.
 * If accessAsAnonymousUser = 'true', object is retrieved as anonymous user.
 * If getObjidFromHref = 'true', and attributes are hrefs,
 * the objId is parsed out of the href./*from   www.j  a  v  a  2  s  . c o m*/
 * 
 * @param restUri restUri
 * @param elementPath path to element
 * @param attributeName path to attribute of element (may be empty)
 * @param attributeNamespaceUri namespaceUri of attribute (May be empty)
 * @param accessAsAnonymousUser 'true' or 'false' or empty (default is false) 
 * @param getObjidFromHref 'true' or 'false' or empty (default is false) 
 * 
 * @return String found attributes whitespace-separated
 */
public static synchronized String getObjectAttribute(final String restUri, final String elementPath,
        final String attributeName, final String attributeNamespaceUri, final String accessAsAnonymousUser,
        final String getObjidFromHref) {

    if (log.isDebugEnabled()) {
        log.debug("executing EscidocCoreAccessor, getObjectAttribute");
    }
    try {
        String result = getXml(restUri, accessAsAnonymousUser);
        if (result == null || "".equals(result)) {
            return "";
        }

        StaxParser sp = new StaxParser();
        ObjectAttributeHandler handler = new ObjectAttributeHandler(sp);
        handler.setAttributeName(attributeName);
        handler.setAttributeNamespaceUri(attributeNamespaceUri);
        handler.setElementPath(elementPath);
        sp.addHandler(handler);

        try {
            sp.parse(new ByteArrayInputStream(result.getBytes(Constants.XML_CHARACTER_ENCODING)));
        } catch (Exception e) {
            e.printStackTrace();
        }

        Vector<String> attributes = handler.getAttributes();
        StringBuffer buf = new StringBuffer("");
        Matcher lastSlashMatcher = Constants.LAST_SLASH_PATTERN.matcher("");
        for (String attribute : attributes) {
            if (getObjidFromHref != null && getObjidFromHref.equals("true")) {
                lastSlashMatcher.reset(attribute);
                if (lastSlashMatcher.reset(attribute).matches()) {
                    buf.append(lastSlashMatcher.group(1)).append(" ");
                }
            } else {
                buf.append(attribute).append(" ");
            }
        }
        return buf.toString();
    } catch (Exception e) {
        log.error("object with uri " + restUri + " not found");
        log.error("", e);
    }
    return "";
}

From source file:com.squarespace.template.TestCaseParser.java

/**
 * Parses a simplistic format of sections annotated by keys:
 *
 *   :<KEY-1>//from   w ww  . j av a2  s  . c  om
 *   [ one or more lines ]
 *
 *   :<KEY-n>
 *   [ one or more lines ]
 */
public static Map<String, String> parseSections(String source) {
    Matcher matcher = RE_SECTION.matcher("");
    String[] lines = RE_LINES.split(source);

    Map<String, String> sections = new HashMap<>();
    String key = null;
    StringBuilder buf = new StringBuilder();

    int size = lines.length;
    for (int i = 0; i < size; i++) {
        matcher.reset(lines[i]);
        if (matcher.lookingAt()) {
            if (key != null) {
                sections.put(key, buf.toString());
                buf.setLength(0);
            }
            key = matcher.group(1);

        } else {
            buf.append('\n');
            buf.append(lines[i]);
        }
    }

    if (!sections.containsKey(key)) {
        sections.put(key, buf.toString());
    }
    return sections;
}

From source file:org.paxle.core.norm.impl.ReferenceNormalizer.java

/**
 * Resolves backpaths/*from ww  w  . j a va2s.  c  om*/
 * @param path The path of an URL
 * @return The path without backpath directives
 */
private static String resolveBackpath(String path) {

    if (path == null || path.length() == 0)
        return "/";
    if (path.length() == 0 || path.charAt(0) != '/') {
        path = "/" + path;
    }

    Matcher matcher = PATH_PATTERN.matcher(path);
    while (matcher.find()) {
        path = matcher.replaceAll("");
        matcher.reset(path);
    }

    return path.equals("") ? "/" : path;
}

From source file:com.qwazr.crawler.web.manager.WebCrawlThread.java

private final static boolean checkRegExpMatcher(String value, List<Matcher> matcherList) {
    for (Matcher matcher : matcherList) {
        matcher.reset(value);
        if (matcher.find())
            return true;
    }//from  w w  w .  ja  va2s  . c  o  m
    return false;
}