Search in sources :

Example 21 with MatchResult

use of java.util.regex.MatchResult in project flexmark-java by vsch.

the class InlineParserImpl method matchWithGroups.

/**
 * If RE matches at current index in the input, advance index and return the match; otherwise return null.
 *
 * @param re pattern to match
 * @return sequence matched or null
 */
@Override
public BasedSequence[] matchWithGroups(Pattern re) {
    if (index >= input.length()) {
        return null;
    }
    Matcher matcher = re.matcher(input);
    matcher.region(index, input.length());
    boolean m = matcher.find();
    if (m) {
        index = matcher.end();
        MatchResult result = matcher.toMatchResult();
        final int iMax = matcher.groupCount() + 1;
        BasedSequence[] results = new BasedSequence[iMax];
        results[0] = input.subSequence(result.start(), result.end());
        for (int i = 1; i < iMax; i++) {
            if (matcher.group(i) != null) {
                results[i] = input.subSequence(result.start(i), result.end(i));
            } else {
                results[i] = null;
            }
        }
        return results;
    } else {
        return null;
    }
}
Also used : Matcher(java.util.regex.Matcher) BasedSequence(com.vladsch.flexmark.util.sequence.BasedSequence) MatchResult(java.util.regex.MatchResult)

Example 22 with MatchResult

use of java.util.regex.MatchResult in project core by CubeEngine.

the class StringUtils method replaceWithCallback.

public static String replaceWithCallback(Pattern pattern, String string, ReplaceCallback callback) {
    final Matcher matcher = pattern.matcher(string);
    while (matcher.find()) {
        final MatchResult matchResult = matcher.toMatchResult();
        final String replacement = callback.replace(matchResult);
        string = string.substring(0, matchResult.start()) + replacement + string.substring(matchResult.end());
        matcher.reset(string);
    }
    return string;
}
Also used : Matcher(java.util.regex.Matcher) MatchResult(java.util.regex.MatchResult)

Example 23 with MatchResult

use of java.util.regex.MatchResult in project wildfly-swarm by wildfly-swarm.

the class SwaggerWebAppDeploymentProducer method swaggerWebApp.

@Produces
public Archive swaggerWebApp() throws ModuleLoadException, IOException {
    // Load the swagger-ui webjars.
    Module module = Module.getBootModuleLoader().loadModule("org.webjars.swagger-ui");
    URL resource = module.getExportedResource("swagger-ui.jar");
    JARArchive webJar = ShrinkWrap.create(JARArchive.class);
    webJar.as(ZipImporter.class).importFrom(resource.openStream());
    JARArchive relocatedJar = ShrinkWrap.create(JARArchive.class);
    Map<ArchivePath, Node> content = webJar.getContent();
    for (ArchivePath path : content.keySet()) {
        Node node = content.get(path);
        Asset asset = node.getAsset();
        if (asset != null) {
            Matcher matcher = PATTERN.matcher(path.get());
            if (matcher.matches()) {
                MatchResult result = matcher.toMatchResult();
                String newPath = "/META-INF/resources/" + result.group(2);
                relocatedJar.add(asset, newPath);
            }
        }
    }
    WARArchive war = ShrinkWrap.create(WARArchive.class, "swagger-ui.war").addAsLibrary(relocatedJar).setContextRoot(this.fraction.getContext());
    war.addClass(SwaggerDefaultUrlChangerServlet.class);
    // If any user content has been provided, merge that with the swagger-ui bits
    Archive<?> userContent = this.fraction.getWebContent();
    if (userContent != null) {
        war.merge(userContent);
    }
    return war;
}
Also used : Matcher(java.util.regex.Matcher) Node(org.jboss.shrinkwrap.api.Node) MatchResult(java.util.regex.MatchResult) WARArchive(org.wildfly.swarm.undertow.WARArchive) URL(java.net.URL) ArchivePath(org.jboss.shrinkwrap.api.ArchivePath) ZipImporter(org.jboss.shrinkwrap.api.importer.ZipImporter) Asset(org.jboss.shrinkwrap.api.asset.Asset) JARArchive(org.wildfly.swarm.spi.api.JARArchive) Module(org.jboss.modules.Module) Produces(javax.enterprise.inject.Produces)

Example 24 with MatchResult

use of java.util.regex.MatchResult in project cassandra by apache.

the class StorageService method rebuild.

public void rebuild(String sourceDc, String keyspace, String tokens, String specificSources) {
    // check ongoing rebuild
    if (!isRebuilding.compareAndSet(false, true)) {
        throw new IllegalStateException("Node is still rebuilding. Check nodetool netstats.");
    }
    // check the arguments
    if (keyspace == null && tokens != null) {
        throw new IllegalArgumentException("Cannot specify tokens without keyspace.");
    }
    logger.info("rebuild from dc: {}, {}, {}", sourceDc == null ? "(any dc)" : sourceDc, keyspace == null ? "(All keyspaces)" : keyspace, tokens == null ? "(All tokens)" : tokens);
    try {
        RangeStreamer streamer = new RangeStreamer(tokenMetadata, null, FBUtilities.getBroadcastAddressAndPort(), StreamOperation.REBUILD, useStrictConsistency && !replacing, DatabaseDescriptor.getEndpointSnitch(), streamStateStore, false, DatabaseDescriptor.getStreamingConnectionsPerHost());
        if (sourceDc != null)
            streamer.addSourceFilter(new RangeStreamer.SingleDatacenterFilter(DatabaseDescriptor.getEndpointSnitch(), sourceDc));
        if (keyspace == null) {
            for (String keyspaceName : Schema.instance.getNonLocalStrategyKeyspaces()) streamer.addRanges(keyspaceName, getLocalReplicas(keyspaceName));
        } else if (tokens == null) {
            streamer.addRanges(keyspace, getLocalReplicas(keyspace));
        } else {
            Token.TokenFactory factory = getTokenFactory();
            List<Range<Token>> ranges = new ArrayList<>();
            Pattern rangePattern = Pattern.compile("\\(\\s*(-?\\w+)\\s*,\\s*(-?\\w+)\\s*\\]");
            try (Scanner tokenScanner = new Scanner(tokens)) {
                while (tokenScanner.findInLine(rangePattern) != null) {
                    MatchResult range = tokenScanner.match();
                    Token startToken = factory.fromString(range.group(1));
                    Token endToken = factory.fromString(range.group(2));
                    logger.info("adding range: ({},{}]", startToken, endToken);
                    ranges.add(new Range<>(startToken, endToken));
                }
                if (tokenScanner.hasNext())
                    throw new IllegalArgumentException("Unexpected string: " + tokenScanner.next());
            }
            // Ensure all specified ranges are actually ranges owned by this host
            RangesAtEndpoint localReplicas = getLocalReplicas(keyspace);
            RangesAtEndpoint.Builder streamRanges = new RangesAtEndpoint.Builder(FBUtilities.getBroadcastAddressAndPort(), ranges.size());
            for (Range<Token> specifiedRange : ranges) {
                boolean foundParentRange = false;
                for (Replica localReplica : localReplicas) {
                    if (localReplica.contains(specifiedRange)) {
                        streamRanges.add(localReplica.decorateSubrange(specifiedRange));
                        foundParentRange = true;
                        break;
                    }
                }
                if (!foundParentRange) {
                    throw new IllegalArgumentException(String.format("The specified range %s is not a range that is owned by this node. Please ensure that all token ranges specified to be rebuilt belong to this node.", specifiedRange.toString()));
                }
            }
            if (specificSources != null) {
                String[] stringHosts = specificSources.split(",");
                Set<InetAddressAndPort> sources = new HashSet<>(stringHosts.length);
                for (String stringHost : stringHosts) {
                    try {
                        InetAddressAndPort endpoint = InetAddressAndPort.getByName(stringHost);
                        if (FBUtilities.getBroadcastAddressAndPort().equals(endpoint)) {
                            throw new IllegalArgumentException("This host was specified as a source for rebuilding. Sources for a rebuild can only be other nodes in the cluster.");
                        }
                        sources.add(endpoint);
                    } catch (UnknownHostException ex) {
                        throw new IllegalArgumentException("Unknown host specified " + stringHost, ex);
                    }
                }
                streamer.addSourceFilter(new RangeStreamer.AllowedSourcesFilter(sources));
            }
            streamer.addRanges(keyspace, streamRanges.build());
        }
        StreamResultFuture resultFuture = streamer.fetchAsync();
        // wait for result
        resultFuture.get();
    } catch (InterruptedException e) {
        throw new UncheckedInterruptedException(e);
    } catch (ExecutionException e) {
        // This is used exclusively through JMX, so log the full trace but only throw a simple RTE
        logger.error("Error while rebuilding node", e.getCause());
        throw new RuntimeException("Error while rebuilding node: " + e.getCause().getMessage());
    } finally {
        // rebuild is done (successfully or not)
        isRebuilding.set(false);
    }
}
Also used : MatchResult(java.util.regex.MatchResult) UncheckedInterruptedException(org.apache.cassandra.utils.concurrent.UncheckedInterruptedException) Arrays.asList(java.util.Arrays.asList) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) Collectors.toList(java.util.stream.Collectors.toList) ExecutionException(java.util.concurrent.ExecutionException) Pattern(java.util.regex.Pattern) UnknownHostException(java.net.UnknownHostException) Range(org.apache.cassandra.dht.Range) FetchReplica(org.apache.cassandra.dht.RangeStreamer.FetchReplica) UncheckedInterruptedException(org.apache.cassandra.utils.concurrent.UncheckedInterruptedException) TokenFactory(org.apache.cassandra.dht.Token.TokenFactory)

Example 25 with MatchResult

use of java.util.regex.MatchResult in project es6draft by anba.

the class RegExpPrototype method RegExpReplace.

private static List<MatchResult> RegExpReplace(ExecutionContext cx, RegExpObject rx, String s, boolean global, boolean fullUnicode) {
    if (!global) {
        /* step 11.a */
        MatchResult result = matchResultOrNull(cx, rx, s, false);
        /* step 11.b */
        if (result == null) {
            return Collections.emptyList();
        }
        /* step 11.c */
        return Collections.singletonList(result);
    }
    /* step 8 */
    /* step 8.a (not applicable) */
    /* step 8.b */
    RegExpSetLastIndex(cx, rx, 0);
    int lastIndex = 0;
    /* step 9 */
    ArrayList<MatchResult> results = new ArrayList<>();
    /* steps 10-11 */
    MatcherState matcher = rx.getRegExpMatcher().matcher(s);
    boolean sticky = rx.isSet(RegExpObject.Flags.Sticky);
    while (true) {
        /* step 11.a */
        boolean matchSucceeded = matchOrFind(matcher, lastIndex, sticky);
        /* step 11.b */
        if (!matchSucceeded) {
            break;
        }
        /* step 11.c */
        MatchResult result = matcher.toMatchResult();
        results.add(result);
        lastIndex = result.end();
        if (result.start() == lastIndex) {
            lastIndex = AdvanceStringIndex(s, lastIndex, fullUnicode);
        }
        if (lastIndex > s.length()) {
            break;
        }
    }
    return results;
}
Also used : ArrayList(java.util.ArrayList) MatcherState(com.github.anba.es6draft.regexp.MatcherState) MatchResult(java.util.regex.MatchResult)

Aggregations

MatchResult (java.util.regex.MatchResult)62 Matcher (java.util.regex.Matcher)26 Pattern (java.util.regex.Pattern)16 Scanner (java.util.Scanner)11 Point (java.awt.Point)5 Test (org.junit.Test)5 ArrayList (java.util.ArrayList)4 IOException (java.io.IOException)3 NoSuchElementException (java.util.NoSuchElementException)3 XMLStreamException (javax.xml.stream.XMLStreamException)3 MatcherState (com.github.anba.es6draft.regexp.MatcherState)2 ArrayObject (com.github.anba.es6draft.runtime.types.builtins.ArrayObject)2 InputStream (java.io.InputStream)2 Fault (org.apache.cxf.interceptor.Fault)2 CachedOutputStream (org.apache.cxf.io.CachedOutputStream)2 IterableMatchResult (com.github.anba.es6draft.regexp.IterableMatchResult)1 MatcherResult (com.github.anba.es6draft.regexp.MatcherResult)1 ScriptObject (com.github.anba.es6draft.runtime.types.ScriptObject)1 OrdinaryObject (com.github.anba.es6draft.runtime.types.builtins.OrdinaryObject)1 ImmutableMap (com.google.common.collect.ImmutableMap)1