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.bireme.interop.toJson.Xml2Json.java

private void getFiles(final File filePath, final Matcher fileNameRegExp, final Matcher fileExtRegExp,
        final boolean recursive, final List<File> out) throws IOException {
    assert filePath != null;
    assert fileNameRegExp != null;
    assert out != null;

    if (filePath.exists()) {
        if (filePath.isFile()) { // regular file
            final String path = filePath.getName();
            final int dot = path.lastIndexOf('.');
            final String fname = (dot == -1) ? path : path.substring(0, dot);
            final String ext = (dot == -1) ? null : path.substring(dot + 1);

            if (fileNameRegExp.reset(fname).matches()) {
                if (fileExtRegExp == null) {
                    if (ext == null) {
                        out.add(filePath);
                    }// w  ww. ja v a  2  s.  c  om
                } else if ((ext != null) && (fileExtRegExp.reset(ext).matches())) {
                    out.add(filePath);
                }
            }
        } else { // directory
            if (recursive) {
                final File[] files = filePath.listFiles();

                if (files != null) {
                    for (File file : filePath.listFiles()) {
                        getFiles(file, fileNameRegExp, fileExtRegExp, recursive, out);
                    }
                }
            }
        }
    }
}

From source file:com.zimbra.common.util.QuotedTextUtil.java

/**
 * Identifies the type of the line by matching it against the regexes
 *
 * @param line A line from the message//  w w  w .ja va  2s  .  c  o  m
 * @return the type of the line
 */
private LineType getLineType(String line) {

    LineType type = LineType.UNKNOWN;

    // see if the line matches any known delimiters or quote patterns
    for (LineType lineType : LineType.values()) {
        boolean matched = false;
        for (Matcher matcher : lineType.getMatcher()) {
            if (matcher.reset(line).matches() || matcher.reset(line.toLowerCase()).matches()) {
                // line that starts and ends with | is considered ASCII art
                // (eg a table) rather than quoted
                if (lineType.name().equals(LineType.QUOTED.name()) && MATCHER_ASCII_ART.reset(line).matches()) {
                    continue;
                }
                matched = true;
                // first match wins
                break;
            }
        }
        if (matched) {
            type = lineType;
            break;
        }
    }

    if (type == LineType.UNKNOWN) {
        /*
         * "so-and-so wrote:" takes a lot of different forms; look for
         * various common parts and assign points to determine confidence
         */
        String[] m = line.split("/(\\w+):$/");
        String verb = m[m.length - 1];

        if (verb != null && !verb.isEmpty()) {
            int points = 0;
            points = points + (verb.contains(WROTE) ? 5 : (verb.contains(CHANGED) ? 2 : 0));
            if (MATCHER_ORIG_EMAIL.reset(line).find()) {
                points += 4;
            }
            if (MATCHER_ORIG_DATE.reset(line).find()) {
                points += 3;
            }
            if (MATCHER_ORIG_INTRO.reset(line.toLowerCase()).find()) {
                points += 1;
            }
            if (points >= 7) {
                type = LineType.WROTE_STRONG;
            } else if (points >= 5) {
                type = LineType.WROTE_WEAK;
            }
        }
    }

    return type;
}

From source file:org.intermine.bio.ontology.OboParser.java

/**
 * Read DAG input line by line to generate hierarchy of DagTerms.
 *
 * @param in text in DAG format/* w  w  w .  j  av  a2 s .co  m*/
 * @throws IOException if anything goes wrong
 */
@SuppressWarnings({ "unchecked", "rawtypes" })
public void readTerms(BufferedReader in) throws IOException {
    String line;
    Map<String, String> tagValues = new MultiValueMap();
    List<Map> termTagValuesList = new ArrayList<Map>();
    List<Map> typeTagValuesList = new ArrayList<Map>();

    Pattern tagValuePattern = Pattern.compile("(.+?[^\\\\]):(.+)");
    Pattern stanzaHeadPattern = Pattern.compile("\\s*\\[(.+)\\]\\s*");
    Matcher tvMatcher = tagValuePattern.matcher("");
    Matcher headMatcher = stanzaHeadPattern.matcher("");

    while ((line = in.readLine()) != null) {
        // First strip off any comments
        if (line.indexOf('!') >= 0) {
            line = line.substring(0, line.indexOf('!'));
        }

        tvMatcher.reset(line);
        headMatcher.reset(line);

        if (headMatcher.matches()) {
            String stanzaType = headMatcher.group(1);
            tagValues = new MultiValueMap(); // cut loose
            if ("Term".equals(stanzaType)) {
                termTagValuesList.add(tagValues);
                LOG.debug("recorded term with " + tagValues.size() + " tag values");
            } else if ("Typedef".equals(stanzaType)) {
                typeTagValuesList.add(tagValues);
                LOG.debug("recorded type with " + tagValues.size() + " tag values");
            } else {
                LOG.warn("Ignoring " + stanzaType + " stanza");
            }
            LOG.debug("matched stanza " + stanzaType);
        } else if (tvMatcher.matches()) {
            String tag = tvMatcher.group(1).trim();
            String value = tvMatcher.group(2).trim();
            tagValues.put(tag, value);
            LOG.debug("matched tag \"" + tag + "\" with value \"" + value + "\"");

            if ("default-namespace".equals(tag)) {
                defaultNS = value;
                LOG.info("default-namespace is \"" + value + "\"");
            }
        }
    }

    in.close();

    // Build the OboTypeDefinition objects
    OboTypeDefinition oboType = new OboTypeDefinition("is_a", "is_a", true);
    types.put(oboType.getId(), oboType);
    for (Iterator<Map> iter = typeTagValuesList.iterator(); iter.hasNext();) {
        Map<?, ?> tvs = iter.next();
        String id = (String) ((List<?>) tvs.get("id")).get(0);
        String name = (String) ((List<?>) tvs.get("name")).get(0);
        boolean isTransitive = isTrue(tvs, "is_transitive");
        oboType = new OboTypeDefinition(id, name, isTransitive);
        types.put(oboType.getId(), oboType);
    }

    // Just build all the OboTerms disconnected
    for (Iterator<Map> iter = termTagValuesList.iterator(); iter.hasNext();) {
        Map<?, ?> tvs = iter.next();
        String id = (String) ((List<?>) tvs.get("id")).get(0);
        String name = (String) ((List<?>) tvs.get("name")).get(0);
        OboTerm term = new OboTerm(id, name);
        term.setObsolete(isTrue(tvs, "is_obsolete"));
        terms.put(term.getId(), term);
    }

    // Now connect them all together
    for (Iterator<Map> iter = termTagValuesList.iterator(); iter.hasNext();) {
        Map<?, ?> tvs = iter.next();
        if (!isTrue(tvs, "is_obsolete")) {
            configureDagTerm(tvs);
        }
    }
}

From source file:candr.yoclip.ParserTest.java

@Test
public void propertyPattern() {
    final ParserOptions<ParserTest> mockParserOptions = createMockParserParameters("+", " ");

    final Parser<ParserTest> testCase = new Parser<ParserTest>(mockParserOptions,
            createMockParserHelpFactory());
    final String expectedPropertyPattern = "P([\\p{Alnum}*$._-]+=\\p{Graph}+)";
    assertThat("property pattern", testCase.getPropertyPattern("P"), is(expectedPropertyPattern));

    final Matcher matcher = Pattern.compile(expectedPropertyPattern).matcher("");
    assertThat("Pkey=value", matcher.reset("Pkey=value").matches(), is(true));
    assertThat("Pkey.key=value*$._-!@#%^&()+={}[]<>,?/",
            matcher.reset("Pkey.key=value*$._-!@#%^&()+={}[]<>,?/").matches(), is(true));
    assertThat("Pkey", matcher.reset("Pkey").matches(), is(false));
    assertThat("Pkey=", matcher.reset("Pkey=").matches(), is(false));
    assertThat("Pkey_key=value", matcher.reset("Pkey_key=value").matches(), is(true));
    assertThat("Pkey-key=value", matcher.reset("Pkey-key=value").matches(), is(true));
    assertThat("Pkey$key=value", matcher.reset("Pkey$key=value").matches(), is(true));
    assertThat("Pkey*key=value", matcher.reset("Pkey*key=value").matches(), is(true));
}

From source file:com.cloudseal.spring.client.namespace.CloudSealBeanDefinitionParserInstance.java

private int getBeanIndex(List list, String regexp) {
    final Pattern pattern = Pattern.compile(regexp);
    final Matcher matcher = pattern.matcher("");
    int index = -1;
    for (int i = 0; i < list.size(); i++) {
        final Object item = list.get(i);
        if (BeanDefinition.class.isInstance(item)) {
            final BeanDefinition filter = (BeanDefinition) item;
            matcher.reset(filter.getBeanClassName());
            if (matcher.find()) {
                index = i;//from   w w  w.j  a  va2 s  .c om
            }
        }
    }
    return index;
}

From source file:com.flipkart.poseidon.serviceclients.generator.ServiceGenerator.java

private JInvocation createRequest(ServiceIDL serviceIdl, JCodeModel jCodeModel, EndPoint endPoint, JBlock block,
        String requestParamWithLimit, String listElementVarName) {
    String baseUri = serviceIdl.getService().getBaseUri();
    String endPointUri = endPoint.getUri();
    String uri = (baseUri + endPointUri).replaceAll("//", "/");
    Set<String> argsList = new LinkedHashSet<>();
    Set<String> argsListQueryParams = new LinkedHashSet<>();

    Matcher matcher = PARAMETERS_PATTERN.matcher(uri);
    while (matcher.find()) {
        uri = matcher.replaceFirst("%s");
        argsList.add(matcher.group(1));//from  www. ja va  2 s  .c  o  m
        matcher.reset(uri);
    }
    if (argsList.isEmpty()) {
        block.decl(jCodeModel.ref("String"), "uri", JExpr.lit(uri));
    } else {
        JInvocation invocation = JExpr.ref("String").invoke("format").arg(uri);
        for (String arg : argsList) {
            Parameter parameter = serviceIdl.getParameters().get(arg);
            if (endPoint.getRequestParamWithLimit() != null && requestParamWithLimit.equals(arg)) {
                arg = listElementVarName;
            }
            if (parameter.getType().equals("String")) {
                invocation.arg(JExpr.invoke("encodeUrl").arg(JExpr.ref(arg)));
            } else if (parameter.getType().endsWith("[]")) {
                JExpression joinerExpression = jCodeModel.ref(Joiner.class).staticInvoke("on")
                        .arg(JExpr.lit(',')).invoke("join").arg(JExpr.ref(arg));
                invocation.arg(JExpr.invoke("encodeUrl").arg(joinerExpression));
            } else if (parameter.getType().startsWith("java.util.List")) {
                invocation.arg(
                        jCodeModel.ref(StringUtils.class).staticInvoke("join").arg(JExpr.ref(arg)).arg(","));
            } else {
                invocation.arg(JExpr.ref(arg));
            }
        }
        block.decl(jCodeModel.ref("String"), "uri", invocation);
    }
    if (endPoint.getParameters() != null) {
        for (String paramName : endPoint.getParameters()) {
            Parameter parameter = serviceIdl.getParameters().get(paramName);
            if (!parameter.getOptional()) {
                if (parameter.getType().equalsIgnoreCase("string") || parameter.getType().endsWith("[]")) {
                    block.add(jCodeModel.ref(Validate.class).staticInvoke("notEmpty").arg(JExpr.ref(paramName))
                            .arg(paramName + " can not be null/empty"));
                } else {
                    block.add(jCodeModel.ref(Validate.class).staticInvoke("notNull").arg(JExpr.ref(paramName))
                            .arg(paramName + " can not be null"));
                }
            }

            if (argsList.contains(paramName))
                continue;

            argsListQueryParams.add(paramName);
        }
    }

    if (!argsListQueryParams.isEmpty()) {
        JInvocation invocation = jCodeModel.ref(Arrays.class).staticInvoke("asList");
        for (String arg : argsListQueryParams) {
            Parameter parameter = serviceIdl.getParameters().get(arg);
            String argRef = arg;
            if (endPoint.getRequestParamWithLimit() != null && requestParamWithLimit.equals(arg)) {
                argRef = listElementVarName;
            }
            String paramName = Optional.ofNullable(parameter.getName()).orElse(arg);
            if (!parameter.getOptional()) {
                if (parameter.isMultiValue()) {
                    invocation.arg(JExpr.invoke("getMultiValueParamURI").arg(paramName).arg(JExpr.ref(argRef)));
                } else if (parameter.getType().equals("String")) {
                    invocation.arg(
                            JExpr.lit(paramName + "=").plus(JExpr.invoke("encodeUrl").arg(JExpr.ref(argRef))));
                } else if (parameter.getType().endsWith("[]")) {
                    JExpression joinerExpression = jCodeModel.ref(Joiner.class).staticInvoke("on")
                            .arg(JExpr.lit(',')).invoke("join").arg(JExpr.ref(argRef));
                    invocation.arg(
                            JExpr.lit(paramName + "=").plus(JExpr.invoke("encodeUrl").arg(joinerExpression)));
                } else if (parameter.getType().startsWith("java.util.List")) {
                    JExpression joinerExpression = jCodeModel.ref(StringUtils.class).staticInvoke("join")
                            .arg(JExpr.ref(argRef)).arg(",");
                    invocation.arg(
                            JExpr.lit(paramName + "=").plus(JExpr.invoke("encodeUrl").arg(joinerExpression)));
                } else {
                    invocation.arg(JExpr.lit(paramName + "=").plus(JExpr.ref(argRef)));
                }
            } else {
                if (parameter.isMultiValue()) {
                    invocation.arg(JExpr.invoke("getMultiValueParamURI").arg(paramName).arg(JExpr.ref(argRef)));
                } else {
                    invocation.arg(JExpr.invoke("getOptURI").arg(paramName).arg(JExpr.ref(argRef)));
                }
            }
        }
        block.assign(JExpr.ref("uri"), JExpr.ref("uri").plus(JExpr.invoke("getQueryURI").arg(invocation)));
    }

    Map<String, String> headersMap = getAllHeaders(serviceIdl, endPoint);
    if (headersMap.size() > 0) {
        JClass mapClass = jCodeModel.ref(Map.class).narrow(jCodeModel.ref("String"), jCodeModel.ref("String"));
        JClass hashMapClass = jCodeModel.ref(HashMap.class).narrow(jCodeModel.ref("String"),
                jCodeModel.ref("String"));
        block.decl(mapClass, "headersMap", JExpr._new(hashMapClass));
        for (Map.Entry<String, String> headerMapEntry : headersMap.entrySet()) {
            String key = headerMapEntry.getKey();
            String value = headerMapEntry.getValue();
            JInvocation invocation = JExpr.invoke(JExpr.ref("headersMap"), "put").arg(key);
            matcher = PARAMETERS_PATTERN.matcher(value);
            if (matcher.find()) {
                String paramName = matcher.group(1);
                invocation.arg(jCodeModel.ref("String").staticInvoke("valueOf").arg(JExpr.ref(paramName)));
                Parameter parameter = serviceIdl.getParameters().get(paramName);
                if (parameter.getOptional()) {
                    block._if(JExpr.ref(paramName).ne(JExpr._null()))._then().add(invocation);
                } else {
                    block.add(invocation);
                }
            } else {
                invocation.arg(value);
                block.add(invocation);
            }
        }
    }

    if (endPoint.getResponseObject() != null && !endPoint.getResponseObject().isEmpty()) {
        // If responseObject contains generic types, use TypeReference. Else use Class of the responseObject.
        // http://wiki.fasterxml.com/JacksonDataBinding
        // For uniformity, TypeReference or Class is then converted to a JavaType to deserialize service response.
        // For generic types, creating an anonymous inner class for every service call would have overhead which is
        // compensated by the type safety it ensures at compilation time as well as easy code generation
        JInvocation invocation = JExpr.invoke("execute");
        JType definedClass = jCodeModel._ref(ServiceExecutePropertiesBuilder.class);
        JInvocation nestedInvocation = JExpr.invoke("getJavaType");
        if (!endPoint.getResponseObject().contains("<")) {
            if (endPoint.getResponseObject().contains(".")) {
                JInvocation classDecl = jCodeModel.ref(Class.class).staticInvoke("forName")
                        .arg(endPoint.getResponseObject());
                nestedInvocation.arg(classDecl);
            } else {
                JFieldRef ref = JExpr.ref(JExpr.ref(endPoint.getResponseObject()), "class");
                nestedInvocation.arg(ref);
            }
        } else {
            JClass typeReferenceClass = jCodeModel.ref(TypeReference.class)
                    .narrow(getJType(jCodeModel, endPoint.getResponseObject()));
            nestedInvocation.arg(JExpr._new(jCodeModel.anonymousClass(typeReferenceClass)));
        }
        JInvocation builderInvocation = JExpr.invoke(JExpr._new(definedClass), "setJavaType")
                .arg(nestedInvocation);
        if (endPoint.getErrorResponseObject() != null && !endPoint.getErrorResponseObject().isEmpty()) {
            JInvocation nestedErrorInvocation = JExpr.invoke("getErrorType");
            if (!endPoint.getErrorResponseObject().contains("<")) {
                if (endPoint.getErrorResponseObject().contains(".")) {
                    JInvocation classDecl = jCodeModel.ref(Class.class).staticInvoke("forName")
                            .arg(endPoint.getErrorResponseObject());
                    nestedErrorInvocation.arg(classDecl);
                } else {
                    JFieldRef ref = JExpr.ref(JExpr.ref(endPoint.getErrorResponseObject()), "class");
                    nestedErrorInvocation.arg(ref);
                }
            } else {
                JClass typeReferenceClass = jCodeModel.ref(TypeReference.class)
                        .narrow(getJType(jCodeModel, endPoint.getErrorResponseObject()));
                nestedErrorInvocation.arg(JExpr._new(jCodeModel.anonymousClass(typeReferenceClass)));
            }
            builderInvocation = builderInvocation.invoke("setErrorType").arg(nestedErrorInvocation);
        }
        builderInvocation = builderInvocation.invoke("setUri").arg(JExpr.ref("uri"));
        builderInvocation = builderInvocation.invoke("setHttpMethod").arg(endPoint.getHttpMethod());

        if (headersMap.size() > 0) {
            builderInvocation = builderInvocation.invoke("setHeadersMap").arg(JExpr.ref("headersMap"));
        }

        if (endPoint.getRequestObject() != null && !endPoint.getRequestObject().isEmpty()) {
            String requestObjectName;
            if (endPoint.getRequestSplitterClass() != null && endPoint.getRequestParamWithLimit() == null) {
                requestObjectName = REQUEST_OBJECT_LOOP_VAR_NAME;
            } else {
                requestObjectName = REQUEST_OBJECT_VAR_NAME;
            }
            builderInvocation = builderInvocation.invoke("setRequestObject").arg(JExpr.ref(requestObjectName));
        }

        if (endPoint.getCommandName() != null && !endPoint.getCommandName().isEmpty()) {
            builderInvocation = builderInvocation.invoke("setCommandName").arg(endPoint.getCommandName());
        }

        if (endPoint.isRequestCachingEnabled()) {
            builderInvocation = builderInvocation.invoke("setRequestCachingEnabled").arg(JExpr.lit(true));
        }
        builderInvocation = builderInvocation.invoke("build");
        return invocation.arg(builderInvocation);
    }
    return null;
}

From source file:org.executequery.gui.editor.QueryEditorTextPanel.java

private void addCommentToRows(int startRow, int endRow) {

    Matcher matcher = sqlCommentMatcher();
    for (int i = startRow; i <= endRow; i++) {

        String text = queryPane.getTextAtRow(i);
        matcher.reset(text);

        if (!matcher.find()) {

            int index = queryPane.getRowStartOffset(i);
            queryPane.insertTextAtOffset(index, SQL_COMMENT);
        }// ww w  . j  av a 2  s  .  c om

    }

}

From source file:org.executequery.gui.editor.QueryEditorTextPanel.java

private void removeCommentFromRows(int startRow, int endRow) throws BadLocationException {

    Document document = queryPane.getDocument();

    Matcher matcher = sqlCommentMatcher();

    for (int i = startRow; i <= endRow; i++) {

        String text = queryPane.getTextAtRow(i);

        matcher.reset(text);

        if (matcher.find()) {

            // retrieve the exact index of '--' since
            // matcher will return first whitespace

            int index = text.indexOf(SQL_COMMENT);
            int startOffset = queryPane.getRowPosition(i);

            document.remove(startOffset + index, 2);
        }//from  www.  ja  va 2 s . c o  m

    }

}

From source file:org.executequery.gui.browser.TreeFindAction.java

protected boolean changed(JComponent comp, String searchString, Position.Bias bias) {

    if (StringUtils.isBlank(searchString)) {

        return false;
    }//  w w  w . j a  va  2  s .com

    JTree tree = (JTree) comp;
    String prefix = searchString;

    if (ignoreCase()) {

        prefix = prefix.toUpperCase();
    }

    boolean wildcardStart = prefix.startsWith("*");
    if (wildcardStart) {

        prefix = prefix.substring(1);

    } else {

        prefix = "^" + prefix;
    }
    prefix = prefix.replaceAll("\\*", ".*");

    Matcher matcher = Pattern.compile(prefix).matcher("");
    List<TreePath> matchedPaths = new ArrayList<TreePath>();
    for (int i = 1; i < tree.getRowCount(); i++) {

        TreePath path = tree.getPathForRow(i);
        String text = tree.convertValueToText(path.getLastPathComponent(), tree.isRowSelected(i),
                tree.isExpanded(i), true, i, false);

        if (ignoreCase()) {

            text = text.toUpperCase();
        }

        //            if ((wildcardStart && text.contains(prefix)) || text.startsWith(prefix, 0)) {
        //
        //                matchedPaths.add(path);
        //            }

        matcher.reset(text);
        if (matcher.find()) {

            matchedPaths.add(path);
        }

    }

    foundValues(matchedPaths);

    return !(matchedPaths.isEmpty());
}

From source file:org.executequery.gui.editor.QueryEditorTextPanel.java

private boolean rowsHaveComments(int startRow, int endRow, boolean allRows) throws BadLocationException {

    Matcher matcher = sqlCommentMatcher();

    for (int i = startRow; i <= endRow; i++) {

        String text = queryPane.getTextAtRow(i);

        matcher.reset(text);

        if (matcher.find()) {

            if (!allRows) {

                return true;

            }//from  w w w. ja v  a  2  s  . c  o m

        } else if (allRows) {

            return false;
        }

    }

    return allRows;
}