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.deegree.feature.persistence.geocouch.GeoCouchFeatureStore.java

private FeatureInputStream queryByOperatorFilter(Query query, QName ftName, OperatorFilter filter)
        throws FeatureStoreException {
    LOG.debug("Performing blob query by operator filter");
    FeatureInputStream result = null;/* ww  w .  ja  va 2  s . co  m*/

    try {
        if (query.getPrefilterBBoxEnvelope() != null) {
            List<String> ids = new ArrayList<String>();
            List<String> blobs = new ArrayList<String>();
            Envelope box = query.getPrefilterBBoxEnvelope();
            Point min = box.getMin();
            Point max = box.getMax();

            Pattern p = Pattern.compile("\"id\"[:]\"([^\"]*)");
            Pattern blob = Pattern.compile("\"value\"[:]\"([^\"]*)");
            Matcher m = p.matcher("nix");
            Matcher blobm = blob.matcher("nix");

            for (TypeName name : query.getTypeNames()) {
                String idxname = name.getFeatureTypeName().toString();
                String url = couchUrl + "/couchBase/default/_design/main/_spatial/"
                        + URLEncoder.encode(idxname, "UTF-8") + "?bbox=";
                url += min.get0() + "," + min.get1() + "," + max.get0() + "," + max.get1();
                List<String> lines = readLines(HttpUtils.get(STREAM, url, null));
                for (String line : lines) {
                    m.reset(line);
                    blobm.reset(line);
                    if (m.find()) {
                        ids.add(m.group(1));
                    }
                    if (blobm.find()) {
                        blobs.add(blobm.group(1));
                    }
                }
            }

            BlobCodec codec = new BlobCodec(schema.getGMLSchema().getVersion(), Compression.NONE);
            result = new IteratorFeatureInputStream(new IDIterator(ids.iterator(), blobs.iterator(), codec));

            // mangle filter to exclude bbox
            if (filter != null && filter.getOperator() instanceof BBOX) {
                filter = null;
            } else if (filter != null && filter.getOperator() instanceof And) {
                And and = (And) filter.getOperator();
                List<Operator> ops = new ArrayList<Operator>();
                for (Operator o : and.getParams()) {
                    if (!(o instanceof BBOX))
                        ops.add(o);
                }
                if (ops.isEmpty()) {
                    filter = null;
                }
                if (ops.size() == 1) {
                    filter = new OperatorFilter(ops.get(0));
                } else {
                    filter = new OperatorFilter(new And(ops.toArray(new Operator[ops.size()])));
                }
            }
        } else {

        }
    } catch (Throwable e) {
        String msg = "Error performing query by operator filter: " + e.getMessage();
        LOG.error(msg, e);
        throw new FeatureStoreException(msg, e);
    }

    if (filter != null) {
        LOG.debug("Applying in-memory post-filtering.");
        result = new FilteredFeatureInputStream(result, filter);
    }

    if (query.getSortProperties().length > 0) {
        LOG.debug("Applying in-memory post-sorting.");
        result = new MemoryFeatureInputStream(
                Features.sortFc(result.toCollection(), query.getSortProperties()));
    }
    return result;
}

From source file:org.springjutsu.validation.ValidationManager.java

/**
 * Responsible for resolving a SPEL expression.
 * Unwraps the EL string, creates an instance of a 
 * @link{SPELReadyRequestContext}, adds all the needed
 * property accessors, and runs the SPEL evaluation.
 * TODO: find a better way to return null if not found on any scope.   
 *  //from  w  w  w .  j  a va  2  s.co  m
 * @param el The EL expression to resolve.
 * @param model The model on which the EL-described field MAY lie.
 * @return The object described by the EL expression.
 */
protected Object resolveSPEL(String elContaining, Object model) {
    // if the whole thing is a single EL string, try to get the object.
    if (elContaining.matches("\\$\\{(.(?!\\$\\{))+\\}")) {
        String resolvableElString = elContaining.substring(2, elContaining.length() - 1) + "?: null";
        Object elResult = spelResolver.get().getBySpel(resolvableElString);
        return elResult;
    } else {
        // otherwise, do string value substitution to build a value.
        String elResolvable = elContaining;
        Matcher matcher = Pattern.compile("\\$\\{(.(?!\\$\\{))+\\}").matcher(elResolvable);
        while (matcher.find()) {
            String elString = matcher.group();
            String resolvableElString = elString.substring(2, elString.length() - 1) + "?: null";
            Object elResult = spelResolver.get().getBySpel(resolvableElString);
            String resolvedElString = elResult != null ? String.valueOf(elResult) : "";
            elResolvable = elResolvable.replace(elString, resolvedElString);
            matcher.reset(elResolvable);
        }
        return elResolvable;
    }
}

From source file:fr.natoine.html.HTMLPage.java

private void finalizeBody() {
    if (body != null && body.length() > 0) {
        Pattern p = Pattern.compile("(<body>)|(<BODY>)");
        Matcher m = p.matcher("");
        m.reset(body);
        body = m.replaceAll("<div id='" + wrapperDiv + "'>");
        p = Pattern.compile("(</body>)|(</BODY>)");
        m = p.matcher("");
        m.reset(body);//from w ww  .j  a  v  a  2 s  .co m
        body = m.replaceAll("</div>");
    } else
        body = "";
}

From source file:fr.natoine.html.HTMLPage.java

public String deleteCommentsNewLine(String _wip_css, String _new_englobing_div) {
    if (_wip_css == null || _wip_css.length() == 0)
        return "";
    // Create a pattern to match comments
    //Pattern p = Pattern.compile("(?:/\\*(?:[^*]|(?:\\*+[^*/]))*\\*+/)|(?://.*)", Pattern.MULTILINE);
    Pattern p = Pattern.compile("(?:/\\*(?:[^*]|(?:\\*+[^*/]))*\\*+/)", Pattern.MULTILINE);
    Matcher m = p.matcher("");
    m.reset(_wip_css);
    String result = m.replaceAll("");
    // Create a pattern to match all new lines and all tabs
    p = Pattern.compile("(\n)|(\t)");
    m = p.matcher("");
    m.reset(result);/*from ww  w.  ja  va2  s . c  o  m*/
    result = m.replaceAll("");
    // Create a pattern to match all multiple " "
    p = Pattern.compile(" (?= )|(?<= ) ");
    m = p.matcher("");
    m.reset(result);
    result = m.replaceAll(" ");
    //creates a pattern to match all }
    p = Pattern.compile("}");
    m = p.matcher("");
    m.reset(result);
    result = m.replaceAll("} #" + _new_englobing_div + " ");
    int cpt_last_spaces_index = result.length();
    while (cpt_last_spaces_index > 0 && result.charAt(cpt_last_spaces_index - 1) == ' ') {
        cpt_last_spaces_index--;
    }
    result = result.substring(0, cpt_last_spaces_index);
    if (result.endsWith("#" + _new_englobing_div))
        result = result.substring(0, result.lastIndexOf("#" + _new_englobing_div));
    result = ("#" + _new_englobing_div + " ").concat(result);
    return result;
}

From source file:com.hdfs.concat.crush.Crush.java

private int findMatcher(Path path) {
    for (int i = 0; i < matchers.size(); i++) {
        Matcher matcher = matchers.get(i);

        matcher.reset(path.toUri().getPath());

        if (matcher.matches()) {
            return i;
        }/*from   www  .  j  ava 2 s.  c o  m*/
    }

    return -1;
}

From source file:com.aliyun.odps.conf.Configuration.java

private String substituteVars(String expr) {
    if (expr == null) {
        return null;
    }//from w  w w. java 2s . c om
    Matcher match = varPat.matcher("");
    String eval = expr;
    for (int s = 0; s < MAX_SUBST; s++) {
        match.reset(eval);
        if (!match.find()) {
            return eval;
        }
        String var = match.group();
        var = var.substring(2, var.length() - 1); // remove ${ .. }
        String val = null;
        try {
            val = System.getProperty(var);
        } catch (SecurityException se) {
            LOG.warn("No permission to get system property: " + var);
        }
        if (val == null) {
            val = getRaw(var);
        }
        if (val == null) {
            return eval; // return literal ${var}: var is unbound
        }
        // substitute
        eval = eval.substring(0, match.start()) + val + eval.substring(match.end());
    }
    throw new IllegalStateException("Variable substitution depth too large: " + MAX_SUBST + " " + expr);
}

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

/**
 * Replace regular expression in a LiteralText object's content.
 * //from   ww w . j  a  v a  2 s .c o m
 * Note: this method does NOT check between object nodes. So if there is a
 * match between the original and one of it's children, it is not parsed.
 * 
 * @param original
 *            The original text.
 * @param matcher
 *            The pattern to search for in the content.
 * @param replacer
 *            The function to call when a match is found in order to supply
 *            a textual replacement.
 * @param useClickHover
 *            Whether or not to parse click and hover actions as well.
 */
public static LiteralText replaceRegex(LiteralText original, Pattern matcher,
        Function<LiteralText, Optional<LiteralText>> replacer, boolean useClickHover) {
    if (original == null) {
        return null;
    }
    List<Text> children = original.getChildren();
    LiteralText.Builder builder = original.toBuilder();
    TextFormat f = builder.getFormat();
    Optional<ClickAction<?>> cl = builder.getClickAction();
    Optional<HoverAction<?>> ho = builder.getHoverAction();
    Optional<ShiftClickAction<?>> sc = builder.getShiftClickAction();
    builder.removeAll();
    String content = builder.getContent();
    if (matcher.matcher(content).find()) {
        Matcher m = matcher.matcher(content);
        if (m.matches()) {
            builder = replacer.apply(builder.build()).orElse(LiteralText.of("")).toBuilder();
        } else {
            String[] parts = content.split(matcher.pattern());
            if (parts.length == 0) {
                String c = content;
                builder = null;
                while ((m = m.reset(c)).find()) {
                    String g = m.group();
                    LiteralText t = replacer.apply(
                            (LiteralText) TextUtils.apply(LiteralText.builder(g).format(f), cl, ho, sc).build())
                            .orElse(LiteralText.of(""));
                    if (builder == null) {
                        builder = t.toBuilder();
                    } else {
                        builder.append(t);
                    }
                    c = m.replaceFirst("");
                }
            } else {
                if (content.startsWith(parts[0])) {
                    List<String> alt = Utils.alternate(parts, allmatches(content, matcher));
                    LiteralText.Builder ob = builder;
                    builder = (LiteralText.Builder) LiteralText.builder();
                    List<String> pz = Utils.al(parts, true);
                    for (String s : alt) {
                        if (pz.contains(s)) {
                            LiteralText t = replaceRegex(bf(s, ob).build(), matcher, replacer, useClickHover);
                            builder.append(t);
                        } else {
                            Optional<LiteralText> t = replacer.apply((LiteralText) TextUtils
                                    .apply(LiteralText.builder(s).format(f), cl, ho, sc).build());
                            builder.append(t.orElse(LiteralText.of("")));
                        }
                    }
                } else {
                    List<String> alt = Utils.alternate(allmatches(content, matcher), parts);
                    LiteralText.Builder ob = builder;
                    builder = (LiteralText.Builder) LiteralText.builder();
                    List<String> pz = Utils.al(parts, true);
                    for (String s : alt) {
                        if (pz.contains(s)) {
                            builder.append(replaceRegex(bf(s, ob).build(), matcher, replacer, useClickHover));
                        } else {
                            Optional<LiteralText> t = replacer.apply((LiteralText) TextUtils
                                    .apply(LiteralText.builder(s).format(f), cl, ho, sc).build());
                            builder.append(t.orElse(LiteralText.of("")));
                        }
                    }
                }
            }
        }
    } else {
        if (builder.getClickAction().isPresent()) {
            boolean r = builder.getClickAction().get() instanceof ClickAction.RunCommand;
            String click = replaceRegexAction(builder.getClickAction().get(), (s) -> {
                if (!matcher.matcher(s).find()) {
                    return s;
                }
                String out = matcher.matcher(s).replaceAll("%s");
                String st = s;
                Matcher m = matcher.matcher(s);
                List<Object> b = Utils.al();
                while ((m = m.reset(st)).find()) {
                    String g = m.group();
                    b.add(replacer.apply(
                            (LiteralText) TextUtils.apply(LiteralText.builder(g).format(f), cl, ho, sc).build())
                            .orElse(LiteralText.builder("").build()).toPlain());
                    st = m.replaceFirst("");
                }
                out = format(out, b);
                return out;
            }, "");
            if (!click.isEmpty()) {
                if (r) {
                    builder.onClick(TextActions.runCommand(click));
                } else {
                    builder.onClick(TextActions.suggestCommand(click));
                }
            }
        }
        if (builder.getHoverAction().isPresent()) {
            Text hover = replaceRegexAction(builder.getHoverAction().get(), (s) -> {
                String a = TextSerializers.FORMATTING_CODE.serialize(s);
                if (!matcher.matcher(a).find()) {
                    return s;
                }
                String out = matcher.matcher(a).replaceAll("%s");
                String st = a;
                Matcher m = matcher.matcher(a);
                List<Object> b = Utils.al();
                while ((m = m.reset(st)).find()) {
                    String g = m.group();
                    b.add(TextSerializers.FORMATTING_CODE.serialize(replacer.apply(
                            (LiteralText) TextUtils.apply(LiteralText.builder(g).format(f), cl, ho, sc).build())
                            .orElse(LiteralText.builder("").build())));
                    st = m.replaceFirst("");
                }
                out = format(out, b);
                return TextSerializers.FORMATTING_CODE.deserialize(out);
            }, Text.of());
            if (!hover.isEmpty()) {
                builder.onHover(TextActions.showText(hover));
            }
        }
    }
    builder.append(children.stream().filter(t -> lit(t))
            .map(child -> replaceRegex((LiteralText) child, matcher, replacer, useClickHover))
            .collect(RayCollectors.rayList()));
    return builder.build();
}

From source file:org.apache.nifi.processors.standard.EvaluateRegularExpression.java

@Override
public void onTrigger(final ProcessContext context, final ProcessSession session) {
    final List<FlowFile> flowFileBatch = session.get(50);
    if (flowFileBatch.isEmpty()) {
        return;//  w  w w.  ja v a 2  s.  c  om
    }
    final ProcessorLog logger = getLogger();

    // Compile the Regular Expressions
    Map<String, Matcher> regexMap = new HashMap<>();
    for (final Map.Entry<PropertyDescriptor, String> entry : context.getProperties().entrySet()) {
        if (!entry.getKey().isDynamic()) {
            continue;
        }
        final int flags = getCompileFlags(context);
        final Matcher matcher = Pattern.compile(entry.getValue(), flags).matcher("");
        regexMap.put(entry.getKey().getName(), matcher);
    }

    final Charset charset = Charset.forName(context.getProperty(CHARACTER_SET).getValue());

    final int maxBufferSize = context.getProperty(MAX_BUFFER_SIZE).asDataSize(DataUnit.B).intValue();

    for (FlowFile flowFile : flowFileBatch) {

        final Map<String, String> regexResults = new HashMap<>();

        final byte[] buffer = new byte[maxBufferSize];

        session.read(flowFile, new InputStreamCallback() {
            @Override
            public void process(InputStream in) throws IOException {
                StreamUtils.fillBuffer(in, buffer, false);
            }
        });

        final int flowFileSize = Math.min((int) flowFile.getSize(), maxBufferSize);

        final String contentString = new String(buffer, 0, flowFileSize, charset);

        for (final Map.Entry<String, Matcher> entry : regexMap.entrySet()) {

            final Matcher matcher = entry.getValue();

            matcher.reset(contentString);

            if (matcher.find()) {
                final String group = matcher.group(1);
                if (!StringUtils.isBlank(group)) {
                    regexResults.put(entry.getKey(), group);
                }
            }
        }

        if (!regexResults.isEmpty()) {
            flowFile = session.putAllAttributes(flowFile, regexResults);
            session.getProvenanceReporter().modifyAttributes(flowFile);
            session.transfer(flowFile, REL_MATCH);
            logger.info("Matched {} Regular Expressions and added attributes to FlowFile {}",
                    new Object[] { regexResults.size(), flowFile });
        } else {
            session.transfer(flowFile, REL_NO_MATCH);
            logger.info("Did not match any Regular Expressions for  FlowFile {}", new Object[] { flowFile });
        }

    } // end flowFileLoop
}

From source file:com.jaeksoft.searchlib.Client.java

public int updateTextDocuments(StreamSource streamSource, String charset, Integer bufferSize,
        String capturePattern, Integer langPosition, List<String> fieldList, InfoCallback infoCallBack)
        throws SearchLibException, IOException, NoSuchAlgorithmException, URISyntaxException,
        InstantiationException, IllegalAccessException, ClassNotFoundException {
    if (capturePattern == null)
        throw new SearchLibException("No capture pattern");
    if (fieldList == null || fieldList.size() == 0)
        throw new SearchLibException("empty field list");
    String[] fields = fieldList.toArray(new String[fieldList.size()]);
    Matcher matcher = Pattern.compile(capturePattern).matcher("");
    BufferedReader br = null;/*  w w w.  j av a 2s. c o m*/
    Reader reader = null;
    SchemaField uniqueSchemaField = getSchema().getFieldList().getUniqueField();
    String uniqueField = uniqueSchemaField != null ? uniqueSchemaField.getName() : null;
    if (charset == null)
        charset = "UTF-8";
    if (bufferSize == null)
        bufferSize = 50;
    try {
        Collection<IndexDocument> docList = new ArrayList<IndexDocument>(bufferSize);
        reader = streamSource.getReader();
        if (reader == null)
            reader = new InputStreamReader(streamSource.getInputStream(), charset);
        br = reader instanceof BufferedReader ? (BufferedReader) reader : new BufferedReader(reader);
        String line;
        int docCount = 0;
        IndexDocument lastDocument = null;
        String lastUniqueValue = null;
        while ((line = br.readLine()) != null) {
            matcher.reset(line);
            if (!matcher.matches())
                continue;
            LanguageEnum lang = LanguageEnum.UNDEFINED;
            int matcherGroupCount = matcher.groupCount();
            if (langPosition != null && matcherGroupCount >= langPosition)
                lang = LanguageEnum.findByNameOrCode(matcher.group(langPosition));
            IndexDocument document = new IndexDocument(lang);
            int i = matcherGroupCount < fields.length ? matcherGroupCount : fields.length;
            String uniqueValue = null;
            while (i > 0) {
                String value = matcher.group(i--);
                String f = fields[i];
                document.add(f, value, 1.0F);
                if (f.equals(uniqueField))
                    uniqueValue = value;
            }
            // Consecutive documents with same uniqueKey value are merged
            // (multivalued)
            if (uniqueField != null && lastDocument != null && uniqueValue != null
                    && uniqueValue.equals(lastUniqueValue)) {
                lastDocument.addIfNotAlreadyHere(document);
                continue;
            }
            docList.add(document);
            if (docList.size() == bufferSize)
                docCount = updateDocList(0, docCount, docList, infoCallBack);
            lastUniqueValue = uniqueValue;
            lastDocument = document;
        }
        if (docList.size() > 0)
            docCount = updateDocList(0, docCount, docList, infoCallBack);
        return docCount;
    } finally {
        if (br != null)
            if (br != reader)
                IOUtils.close(br);
    }
}

From source file:de.escidoc.core.common.business.indexing.IndexingHandler.java

/**
 * Get configuration for available indexes.
 *
 * @throws IOException     e/*from   ww w. j a  va 2  s. c o  m*/
 * @throws SystemException e
 */
private void getIndexConfigs() throws IOException, SystemException {
    // Build IndexInfo HashMap
    this.objectTypeParameters = new HashMap<String, Map<String, Map<String, Object>>>();
    final String searchPropertiesDirectory = EscidocConfiguration.getInstance()
            .get(EscidocConfiguration.SEARCH_PROPERTIES_DIRECTORY);
    for (final String indexName : getIndexNames()) {
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("getting configuration for index " + indexName);
        }
        final Properties indexProps = new Properties();
        InputStream propStream = null;
        try {
            try {
                propStream = getInputStream('/' + searchPropertiesDirectory + "/index/" + indexName
                        + "/index.object-types.properties");
            } catch (IOException e) {
                propStream = IndexingHandler.class.getResourceAsStream('/' + searchPropertiesDirectory
                        + "/index/" + indexName + "/index.object-types.properties");
            }
            if (propStream == null) {
                throw new SystemException(searchPropertiesDirectory + "/index/" + indexName
                        + "/index.object-types.properties " + "not found");
            }
            indexProps.load(propStream);
        } finally {
            IOUtils.closeStream(propStream);
        }
        final Pattern objectTypePattern = Pattern.compile(".*?\\.(.*?)\\..*");
        final Matcher objectTypeMatcher = objectTypePattern.matcher("");
        final Collection<String> objectTypes = new HashSet<String>();
        for (final Object o : indexProps.keySet()) {
            final String key = (String) o;
            if (key.startsWith("Resource")) {
                final String propVal = indexProps.getProperty(key);
                if (LOGGER.isDebugEnabled()) {
                    LOGGER.debug("found property " + key + ':' + propVal);
                }
                objectTypeMatcher.reset(key);
                if (!objectTypeMatcher.matches()) {
                    throw new IOException(key + " is not a supported property");
                }
                final String objectType = de.escidoc.core.common.business.Constants.RESOURCES_NS_URI
                        + objectTypeMatcher.group(1);
                if (objectTypeParameters.get(objectType) == null) {
                    if (LOGGER.isDebugEnabled()) {
                        LOGGER.debug("initializing HashMap for objectType " + objectType);
                    }
                    objectTypeParameters.put(objectType, new HashMap<String, Map<String, Object>>());
                }
                if (objectTypeParameters.get(objectType).get(indexName) == null) {
                    objectTypeParameters.get(objectType).put(indexName, new HashMap<String, Object>());
                    if (LOGGER.isDebugEnabled()) {
                        LOGGER.debug("adding " + indexName + " to " + objectType);
                    }
                    objectTypes.add(objectType);
                }
                if (key.contains("Prerequisite")) {
                    if (objectTypeParameters.get(objectType).get(indexName).get("prerequisites") == null) {
                        objectTypeParameters.get(objectType).get(indexName).put("prerequisites",
                                new HashMap<String, String>());
                    }
                    ((Map<String, String>) objectTypeParameters.get(objectType).get(indexName)
                            .get("prerequisites")).put(key.replaceFirst(".*\\.", ""), propVal);
                    if (LOGGER.isDebugEnabled()) {
                        LOGGER.debug("adding prerequisite " + key + ':' + propVal);
                    }
                } else {
                    objectTypeParameters.get(objectType).get(indexName).put(key.replaceFirst(".*\\.", ""),
                            propVal);
                    if (LOGGER.isDebugEnabled()) {
                        LOGGER.debug("adding parameter " + key + ':' + propVal);
                    }
                }
            }
        }
        for (final String objectType : objectTypes) {
            if (objectTypeParameters.get(objectType).get(indexName).get("indexAsynchronous") == null) {
                objectTypeParameters.get(objectType).get(indexName).put("indexAsynchronous", "false");
            }
            if (objectTypeParameters.get(objectType).get(indexName).get("indexReleasedVersion") == null) {
                objectTypeParameters.get(objectType).get(indexName).put("indexReleasedVersion", "false");
            }
        }
    }
}