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:me.Wundero.Ray.utils.TextUtils.java

private static String[] allmatches(final String a, final Pattern b) {
    String f = a;/* w  w w .  j a  va 2 s .c  o  m*/
    Matcher m = b.matcher(f);
    List<String> o = Utils.al();
    while ((m = m.reset(f)).find()) {
        o.add(m.group());
        f = m.replaceFirst("");
    }
    return o.toArray(new String[o.size()]);
}

From source file:me.Wundero.Ray.utils.TextUtils.java

/**
 * Split the text at a regular expression. If skip, pattern will be skipped.
 *///from  w w  w.  j  ava  2  s  .c o  m
public static List<Text> split(Text t, Pattern p, boolean skip) {
    if (!lit(t)) {
        return Utils.al(t);
    }
    List<Text> out = Utils.al();
    List<Text> children = t.getChildren();
    LiteralText.Builder text = ((LiteralText) t).toBuilder();
    String content = text.getContent();
    if (!p.matcher(content).find()) {
        return Utils.al(t);
    }
    if (p.matcher(content).matches()) {
        return skip ? Utils.al() : Utils.al(t);
    }
    Matcher m = p.matcher(content);
    while ((m = m.reset(content)).find()) {
        int s = m.start();
        int e = m.end();
        Text.Builder b = Text.builder(content.substring(0, s)).format(text.getFormat());
        b = apply(b, text);
        out.add(b.build());
        if (!skip) {
            b = Text.builder(m.group()).format(text.getFormat());
            b = apply(b, text);
            out.add(b.build());
        }
        content = content.substring(0, e);
    }
    if (!content.isEmpty()) {
        Text.Builder b = Text.builder(content).format(text.getFormat());
        b = apply(b, text);
        out.add(b.build());
    }
    Text.Builder tx = out.get(out.size() - 1).toBuilder();
    out.remove(out.size() - 1);
    for (Text child : children) {
        List<Text> lt = split(child, p, skip);
        if (lt.isEmpty()) {
            out.add(tx.build());
            tx = null;
        } else if (lt.size() == 1) {
            tx = tx == null ? lt.get(0).toBuilder() : tx.append(lt.get(0));
        } else {
            out.add(tx == null ? lt.get(0) : tx.append(lt.get(0)).build());
            for (int i = 1; i < lt.size() - 1; i++) {
                out.add(lt.get(i));
            }
            tx = tx == null ? lt.get(lt.size() - 1).toBuilder() : lt.get(lt.size() - 1).toBuilder();
        }
    }
    if (tx != null) {
        out.add(tx.build());
    }
    return out;
}

From source file:chatbot.Chatbot.java

/** **************************************************************************************************
 * Remove punctuation and contractions from a sentence.
 * @return the sentence in a String minus these elements.
 *///from w ww.ja  v  a  2s  .  c  o  m
public String removePunctuation(String sentence) {

    Matcher m = null;
    if (isNullOrEmpty(sentence))
        return sentence;
    m = Pattern.compile("(\\w)\\'re").matcher(sentence);
    while (m.find()) {
        //System.out.println("matches");
        String group = m.group(1);
        sentence = m.replaceFirst(group).toString();
        m.reset(sentence);
    }
    m = Pattern.compile("(\\w)\\'m").matcher(sentence);
    while (m.find()) {
        //System.out.println("matches");
        String group = m.group(1);
        sentence = m.replaceFirst(group).toString();
        m.reset(sentence);
    }
    m = Pattern.compile("(\\w)n\\'t").matcher(sentence);
    while (m.find()) {
        //System.out.println("matches");
        String group = m.group(1);
        sentence = m.replaceFirst(group).toString();
        m.reset(sentence);
    }
    m = Pattern.compile("(\\w)\\'ll").matcher(sentence);
    while (m.find()) {
        //System.out.println("matches");
        String group = m.group(1);
        sentence = m.replaceFirst(group).toString();
        m.reset(sentence);
    }
    m = Pattern.compile("(\\w)\\'s").matcher(sentence);
    while (m.find()) {
        //System.out.println("matches");
        String group = m.group(1);
        sentence = m.replaceFirst(group).toString();
        m.reset(sentence);
    }
    m = Pattern.compile("(\\w)\\'d").matcher(sentence);
    while (m.find()) {
        //System.out.println("matches");
        String group = m.group(1);
        sentence = m.replaceFirst(group).toString();
        m.reset(sentence);
    }
    m = Pattern.compile("(\\w)\\'ve").matcher(sentence);
    while (m.find()) {
        //System.out.println("matches");
        String group = m.group(1);
        sentence = m.replaceFirst(group).toString();
        m.reset(sentence);
    }
    sentence = sentence.replaceAll("\\'", "");
    sentence = sentence.replaceAll("\"", "");
    sentence = sentence.replaceAll("\\.", "");
    sentence = sentence.replaceAll("\\;", "");
    sentence = sentence.replaceAll("\\:", "");
    sentence = sentence.replaceAll("\\?", "");
    sentence = sentence.replaceAll("\\!", "");
    sentence = sentence.replaceAll("\\, ", " ");
    sentence = sentence.replaceAll("\\,[^ ]", ", ");
    sentence = sentence.replaceAll("  ", " ");
    return sentence;
}

From source file:org.structr.core.module.ModuleService.java

/**
 * Scans the class path and returns a Set containing all structr modules.
 *
 * @return a Set of active module names/*from  w w w .  j a  va 2 s. c  om*/
 */
public Set<String> getResourcesToScan() {

    String classPath = System.getProperty("java.class.path");
    Set<String> ret = new LinkedHashSet<String>();
    Pattern pattern = Pattern.compile(".*(structr).*(war|jar)");
    Matcher matcher = pattern.matcher("");

    for (String jarPath : classPath.split("[".concat(pathSep).concat("]+"))) {

        String lowerPath = jarPath.toLowerCase();

        if (lowerPath.endsWith(classesDir) || lowerPath.endsWith(testClassesDir)) {

            ret.add(jarPath);

        } else {

            String moduleName = lowerPath.substring(lowerPath.lastIndexOf(pathSep) + 1);

            matcher.reset(moduleName);

            if (matcher.matches()) {

                ret.add(jarPath);
            }

        }

    }

    String resources = Services.getResources();

    if (resources != null) {

        for (String resource : resources.split("[".concat(pathSep).concat("]+"))) {

            String lowerResource = resource.toLowerCase();

            if (lowerResource.endsWith(".jar") || lowerResource.endsWith(".war")) {

                ret.add(resource);
            }

        }

    }

    // logger.log(Level.INFO, "resources: {0}", ret);

    return (ret);

}

From source file:de.escidoc.core.test.sb.SearchTestBase.java

/**
 * check if public-status, version-number and latest-version-numer are as expected.
 * //from ww  w  .ja  v  a 2  s . c om
 * @param xml
 *            String searchResult
 * @param versionCheckMap
 *            HashMap with objectIds + expected version info.
 * @throws Exception
 *             e
 */
protected void checkVersions(final String xml, final Map<String, HashMap<String, String>> versionCheckMap)
        throws Exception {
    Document doc = getDocument(xml);
    Pattern objIdPattern = Pattern.compile("\\$\\{objId\\}");
    Matcher objIdMatcher = objIdPattern.matcher("");
    Pattern objTypePattern = Pattern.compile("\\$\\{objType\\}");
    Matcher objTypeMatcher = objTypePattern.matcher("");
    String publicStatusXpath = "//${objType}[@href=\"${objId}" + "\"]/properties/public-status";
    String versionNumberXpath = "//${objType}[@href=\"${objId}" + "\"]/properties/version/number";
    String latestVersionNumberXpath = "//${objType}[@href=\"${objId}" + "\"]/properties/latest-version/number";

    for (String key : versionCheckMap.keySet()) {
        objIdMatcher.reset(publicStatusXpath);
        String replacedPublicStatusXpath = objIdMatcher.replaceFirst(key);
        objTypeMatcher.reset(replacedPublicStatusXpath);
        replacedPublicStatusXpath = objTypeMatcher.replaceFirst(versionCheckMap.get(key).get("objectType"));

        objIdMatcher.reset(versionNumberXpath);
        String replacedVersionNumberXpath = objIdMatcher.replaceFirst(key);
        objTypeMatcher.reset(replacedVersionNumberXpath);
        replacedVersionNumberXpath = objTypeMatcher.replaceFirst(versionCheckMap.get(key).get("objectType"));

        objIdMatcher.reset(latestVersionNumberXpath);
        String replacedLatestVersionNumberXpath = objIdMatcher.replaceFirst(key);
        objTypeMatcher.reset(replacedLatestVersionNumberXpath);
        replacedLatestVersionNumberXpath = objTypeMatcher
                .replaceFirst(versionCheckMap.get(key).get("objectType"));

        Node publicStatus = selectSingleNode(doc, replacedPublicStatusXpath);
        Node versionNumber = selectSingleNode(doc, replacedVersionNumberXpath);
        Node latestVersionNumber = selectSingleNode(doc, replacedLatestVersionNumberXpath);
        assertEquals("Public-Status not as expected", versionCheckMap.get(key).get("expectedPublicStatus"),
                publicStatus.getTextContent());
        assertEquals("Version-Number not as expected", versionCheckMap.get(key).get("expectedVersionNumber"),
                versionNumber.getTextContent());
        assertEquals("Latest-Version-Number not as expected",
                versionCheckMap.get(key).get("expectedLatestVersionNumber"),
                latestVersionNumber.getTextContent());
    }
}

From source file:me.Wundero.Ray.utils.TextUtils.java

/**
 * Find all variables in a string and parse it into a text template.
 *//*from w ww.j  av  a2  s  . co  m*/
public static TextTemplate parse(final String i, boolean allowColors) {
    if (i == null) {
        return null;
    }
    String in = i;
    if (!allowColors) {
        in = strip(in);
    }
    in = in.replace("%n", "\n");
    if (!Utils.VAR_PATTERN.matcher(in).find()) {
        return TextTemplate.of(TextSerializers.FORMATTING_CODE.deserialize(in));
    }
    String[] textParts = in.split(Utils.VAR_PATTERN.pattern());
    if (textParts.length == 0) {
        return TextTemplate.of(TextTemplate.arg(in));
    }
    Matcher matcher = Utils.VAR_PATTERN.matcher(in);
    TextTemplate out = TextTemplate.of(TextSerializers.FORMATTING_CODE.deserialize(textParts[0]));
    int x = 1;
    while (matcher.reset(in).find()) {
        String mg = matcher.group().substring(1);
        mg = mg.substring(0, mg.length() - 1);
        out = out.concat(TextTemplate.of(TextTemplate.arg(mg)));
        if (x < textParts.length) {
            out = out.concat(TextTemplate.of(TextSerializers.FORMATTING_CODE.deserialize(textParts[x])));
        }
        in = matcher.replaceFirst("");
        x++;
    }
    return out;
}

From source file:org.kuali.rice.core.impl.config.property.JAXBConfigImpl.java

/**
 * This method parses the value string to find all nested properties (foo=${nested}) and
 * replaces them with the value returned from calling resolve(). It does this in a new string
 * and does not modify the raw or resolved properties objects.
 * /*from   w  ww.java 2 s. co  m*/
 * @param value the string to search for nest properties
 * @param keySet contains all keys used so far in this recursion. used to check for circular
 *        references.
 * @return
 */
protected String parseValue(String value, Set<String> keySet) {
    String result = value;

    Matcher matcher = pattern.matcher(value);

    while (matcher.find()) {

        // get the first, outermost ${} in the string. removes the ${} as well.
        String key = matcher.group(1);

        String resolved = resolve(key, keySet);

        result = matcher.replaceFirst(Matcher.quoteReplacement(resolved));
        matcher = matcher.reset(result);
    }

    return result;
}

From source file:org.apache.nifi.processors.aws.wag.AbstractAWSGatewayApiProcessor.java

protected GenericApiGatewayRequestBuilder setHeaderProperties(final ProcessContext context,
        GenericApiGatewayRequestBuilder requestBuilder, HttpMethodName methodName,
        final FlowFile requestFlowFile) {

    Map<String, String> headers = new HashMap<>();
    for (String headerKey : dynamicPropertyNames) {
        String headerValue = context.getProperty(headerKey).evaluateAttributeExpressions(requestFlowFile)
                .getValue();/*from   w  w  w  .ja  v  a2s . c o  m*/
        headers.put(headerKey, headerValue);
    }

    // iterate through the flowfile attributes, adding any attribute that
    // matches the attributes-to-send pattern. if the pattern is not set
    // (it's an optional property), ignore that attribute entirely
    if (regexAttributesToSend != null && requestFlowFile != null) {
        Map<String, String> attributes = requestFlowFile.getAttributes();
        Matcher m = regexAttributesToSend.matcher("");
        for (Map.Entry<String, String> entry : attributes.entrySet()) {
            String headerKey = trimToEmpty(entry.getKey());

            // don't include any of the ignored attributes
            if (IGNORED_ATTRIBUTES.contains(headerKey)) {
                continue;
            }

            // check if our attribute key matches the pattern
            // if so, include in the request as a header
            m.reset(headerKey);
            if (m.matches()) {
                String headerVal = trimToEmpty(entry.getValue());
                headers.put(headerKey, headerVal);
            }
        }
    }

    String contentType = context.getProperty(PROP_CONTENT_TYPE).evaluateAttributeExpressions(requestFlowFile)
            .getValue();
    boolean sendBody = context.getProperty(PROP_SEND_BODY).asBoolean();
    contentType = StringUtils.isBlank(contentType) ? DEFAULT_CONTENT_TYPE : contentType;
    if (methodName == HttpMethodName.PUT || methodName == HttpMethodName.POST
            || methodName == HttpMethodName.PATCH) {
        if (sendBody) {
            headers.put("Content-Type", contentType);
        }
    } else {
        headers.put("Content-Type", contentType);
    }

    if (!headers.isEmpty()) {
        requestBuilder = requestBuilder.withHeaders(headers);
    }

    return requestBuilder;
}

From source file:com.krawler.common.util.StringUtil.java

/**
 * Substitutes all occurrences of the specified values into a template. Keys
 * for the values are specified in the template as <code>${KEY_NAME}</code>.
 *
 * @param template//from w  w w  .  j av a 2s  . com
 *            the template
 * @param vars
 *            a <code>Map</code> filled with keys and values. The keys
 *            must be <code>String</code>s.
 * @return the template with substituted values
 */
public static String fillTemplate(String template, Map vars) {
    if (template == null) {
        return null;
    }

    String line = template;
    Matcher matcher = templatePattern.matcher(line);

    // Substitute multiple variables per line
    while (matcher.matches()) {
        String key = matcher.group(2);
        Object value = vars.get(key);
        if (value == null) {
            KrawlerLog.misc.info("fillTemplate(): could not find key '" + key + "'");
            value = "";
        }
        line = matcher.group(1) + value + matcher.group(3);
        matcher.reset(line);
    }
    return line;
}

From source file:com.agiletec.plugins.jpnewsletter.aps.system.services.newsletter.NewsletterManager.java

protected String parseText(String defaultText, Map<String, String> params) {
    String body = defaultText;//from w w  w .j  a v  a 2  s  . c  o m
    for (Entry<String, String> pairs : params.entrySet()) {
        String regExp = "\\{" + pairs.getKey() + "\\}";
        Pattern pattern = Pattern.compile(regExp);
        Matcher codeMatcher = pattern.matcher("");
        codeMatcher.reset(body);
        if (codeMatcher.find()) {
            body = codeMatcher.replaceAll((String) pairs.getValue());
        }
    }
    return body;
}