Example usage for java.util.regex Matcher end

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

Introduction

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

Prototype

public int end() 

Source Link

Document

Returns the offset after the last character matched.

Usage

From source file:com.afousan.service.RetwisRepository.java

private String replaceReplies(String content) {
    Matcher regexMatcher = MENTION_REGEX.matcher(content);
    while (regexMatcher.find()) {
        String match = regexMatcher.group();
        int start = regexMatcher.start();
        int stop = regexMatcher.end();

        String uName = match.substring(1);
        if (isUserValid(uName)) {
            content = content.substring(0, start) + "<a href=\"!" + uName + "\">" + match + "</a>"
                    + content.substring(stop);
        }/*w  ww. j ava  2  s .  c o m*/
    }
    return content;
}

From source file:be.makercafe.apps.makerbench.editors.XMLEditor.java

private StyleSpans<Collection<String>> computeHighlighting(String text) {
    Matcher matcher = XML_TAG.matcher(text);
    int lastKwEnd = 0;
    StyleSpansBuilder<Collection<String>> spansBuilder = new StyleSpansBuilder<>();
    while (matcher.find()) {
        spansBuilder.add(Collections.emptyList(), matcher.start() - lastKwEnd);
        if (matcher.group("COMMENT") != null) {
            spansBuilder.add(Collections.singleton("comment"), matcher.end() - matcher.start());
        } else {/* w w w  . ja  va 2 s  .  c om*/
            if (matcher.group("ELEMENT") != null) {
                String attributesText = matcher.group(GROUP_ATTRIBUTES_SECTION);
                spansBuilder.add(Collections.singleton("tagmark"),
                        matcher.end(GROUP_OPEN_BRACKET) - matcher.start(GROUP_OPEN_BRACKET));
                spansBuilder.add(Collections.singleton("anytag"),
                        matcher.end(GROUP_ELEMENT_NAME) - matcher.end(GROUP_OPEN_BRACKET));
                if (!attributesText.isEmpty()) {
                    lastKwEnd = 0;
                    Matcher amatcher = ATTRIBUTES.matcher(attributesText);
                    while (amatcher.find()) {
                        spansBuilder.add(Collections.emptyList(), amatcher.start() - lastKwEnd);
                        spansBuilder.add(Collections.singleton("attribute"),
                                amatcher.end(GROUP_ATTRIBUTE_NAME) - amatcher.start(GROUP_ATTRIBUTE_NAME));
                        spansBuilder.add(Collections.singleton("tagmark"),
                                amatcher.end(GROUP_EQUAL_SYMBOL) - amatcher.end(GROUP_ATTRIBUTE_NAME));
                        spansBuilder.add(Collections.singleton("avalue"),
                                amatcher.end(GROUP_ATTRIBUTE_VALUE) - amatcher.end(GROUP_EQUAL_SYMBOL));
                        lastKwEnd = amatcher.end();
                    }
                    if (attributesText.length() > lastKwEnd)
                        spansBuilder.add(Collections.emptyList(), attributesText.length() - lastKwEnd);
                }
                lastKwEnd = matcher.end(GROUP_ATTRIBUTES_SECTION);
                spansBuilder.add(Collections.singleton("tagmark"),
                        matcher.end(GROUP_CLOSE_BRACKET) - lastKwEnd);
            }
        }
        lastKwEnd = matcher.end();
    }
    spansBuilder.add(Collections.emptyList(), text.length() - lastKwEnd);
    return spansBuilder.create();
}

From source file:com.timrae.rikaidroid.MainActivity.java

/**
 * Reinflect the reading returned by Aedict according to the original word
 * @param original original word looked up by Aedict
 * @param kanji kanji of result returned by Aedict (after de-inflection)
 * @param reading reading of result returned by Aedict (after de-inflection)
 * @return what the reading would look like before the de-inflection
 *//*from  w ww .j  a  v a 2 s  .  c  om*/
private String reinflectReading(String original, String kanji, String reading) {
    Matcher matcher = KANJI_REGEXP.matcher(kanji);
    int end = 0;
    while (matcher.find()) {
        // do nothing so that we get the last hit
        end = matcher.end();
    }
    String originalVerbEnding = original.substring(end);
    String newVerbEnding = kanji.substring(end);
    String readingBase = reading.substring(0, reading.length() - newVerbEnding.length());
    return readingBase + originalVerbEnding;
}

From source file:gate.tagger.tagme.TaggerTagMeWS.java

protected void annotateText(Document doc, AnnotationSet outputAS, long from, long to) {
    String text = "";
    try {// w  w  w . java  2 s  . co  m
        text = doc.getContent().getContent(from, to).toString();
    } catch (InvalidOffsetException ex) {
        throw new GateRuntimeException("Unexpected offset exception, offsets are " + from + "/" + to);
    }
    // send the text to the service and get back the response
    //System.out.println("Annotating text: "+text);
    //System.out.println("Starting offset is "+from);

    // NOTE: there is a bug in the TagMe service which causes offset errors
    // if we use the tweet mode and there are certain patterns in the tweet.
    // The approach recommended by Francesco Piccinno is to replace those 
    // patterns by spaces.    
    if (getIsTweet()) {
        logger.debug("Text before cleaning: >>" + text + "<<");
        // replace 
        text = text.replaceAll(patternStringRT3, "    ");
        text = text.replaceAll(patternStringRT2, "   ");
        text = text.replaceAll(patternHashTag, " $1");
        // now replace the remaining patterns by spaces
        StringBuilder sb = new StringBuilder(text);
        Matcher m = patternUrl.matcher(text);
        while (m.find()) {
            int start = m.start();
            int end = m.end();
            sb.replace(start, end, nSpaces(end - start));
        }
        m = patternUser.matcher(text);
        while (m.find()) {
            int start = m.start();
            int end = m.end();
            sb.replace(start, end, nSpaces(end - start));
        }
        text = sb.toString();
        logger.debug("Text after cleaning:  >>" + text + "<<");
    }
    TagMeAnnotation[] tagmeAnnotations = getTagMeAnnotations(text);
    for (TagMeAnnotation tagmeAnn : tagmeAnnotations) {
        if (tagmeAnn.rho >= minrho) {
            FeatureMap fm = Factory.newFeatureMap();
            fm.put("tagMeId", tagmeAnn.id);
            fm.put("title", tagmeAnn.title);
            fm.put("rho", tagmeAnn.rho);
            fm.put("spot", tagmeAnn.spot);
            fm.put("link_probability", tagmeAnn.link_probability);
            if (tagmeAnn.title == null) {
                throw new GateRuntimeException("Odd: got a null title from the TagMe service" + tagmeAnn);
            } else {
                fm.put("inst", "http://dbpedia.org/resource/" + recodeForDbp38(tagmeAnn.title));
            }
            try {
                gate.Utils.addAnn(outputAS, from + tagmeAnn.start, from + tagmeAnn.end,
                        getOutputAnnotationType(), fm);
            } catch (Exception ex) {
                System.err.println(
                        "Got an exception in document " + doc.getName() + ": " + ex.getLocalizedMessage());
                ex.printStackTrace(System.err);
                System.err.println("from=" + from + ", to=" + to + " TagMeAnn=" + tagmeAnn);
            }
        }
    }
}

From source file:sapience.injectors.stax.inject.StringBasedStaxStreamInjector.java

/**
 * Helper method, takes an XML reference with local namespace definitions, and returns the namespaces as QNames
 * @param xml/*from  w  ww  . j a v a  2 s .  c om*/
 * @return
 */
private List<QName> extractNamespaces(String xml) {
    List<QName> res = new ArrayList<QName>();

    Matcher nsMatcher = nsPattern.matcher(xml);
    while (nsMatcher.find()) {
        int start = nsMatcher.start();
        int end = nsMatcher.end();
        StringBuilder sbu = new StringBuilder(xml.substring(start, end));
        String prefix = sbu.substring(sbu.indexOf(":") + 1, sbu.lastIndexOf("="));
        String uri = sbu.substring(sbu.indexOf("\"") + 1, sbu.lastIndexOf("\""));
        res.add(new QName(uri, prefix));
    }
    return res;
}

From source file:br.msf.commons.util.CharSequenceUtils.java

@SuppressWarnings("unchecked")
public static List<MatchEntry> findPattern(final Pattern pattern, final CharSequence sequence) {
    if (pattern == null || isEmptyOrNull(sequence)) {
        return CollectionUtils.EMPTY_LIST;
    }//from   w w w.j a  v a2s  . co  m
    final Matcher matcher = pattern.matcher(sequence);
    final List<MatchEntry> occurrences = new ArrayList<MatchEntry>();
    while (matcher.find()) {
        occurrences.add(new MatchEntry(matcher.start(), matcher.end()));
    }
    return occurrences;
}

From source file:hudson.plugins.simpleupdatesite.HPI.java

public List<Developer> getDevelopers(Attributes attributes) throws IOException {
    String devs = attributes.getValue("Plugin-Developers");
    if (devs == null || devs.trim().length() == 0) {
        return Collections.emptyList();
    }/*w  ww  .  j a v  a  2  s.  co m*/

    List<Developer> result = new ArrayList<Developer>();
    Matcher matcher = this.developersPattern.matcher(devs);
    int totalMatched = 0;
    while (matcher.find()) {
        result.add(new Developer(StringUtils.trimToEmpty(matcher.group(1)),
                StringUtils.trimToEmpty(matcher.group(2)), StringUtils.trimToEmpty(matcher.group(3))));
        totalMatched += matcher.end() - matcher.start();
    }
    if (totalMatched < devs.length()) {
        // ignore and move on
        System.err.println("Unparsable developer info: '" + devs.substring(totalMatched) + "'");
    }
    return result;
}

From source file:com.sangupta.dryrun.mongo.DryRunAntPath.java

/**
 * Returns the regular expression equivalent of this Ant path.
 * /*from  www.  j a  v  a  2  s  .c om*/
 * @return
 */
public String toRegex() {

    StringBuilder patternBuilder = new StringBuilder();
    Matcher m = WILDCARD_PATTERN.matcher(path);
    int end = 0;

    while (m.find()) {

        patternBuilder.append(quote(path, end, m.start()));
        String match = m.group();

        if ("?".equals(match)) {
            patternBuilder.append('.');
        } else if ("**".equals(match)) {
            patternBuilder.append(".*");
        } else if ("*".equals(match)) {
            patternBuilder.append("[^/]*");
        }

        end = m.end();
    }

    patternBuilder.append(quote(path, end, path.length()));
    return patternBuilder.toString();
}

From source file:com.google.acre.appengine.script.AppEngineAsyncUrlfetch.java

private Scriptable callback_result(AsyncRequest req, HTTPResponse res) {

    long waiting_time = System.currentTimeMillis() - req.start_time;

    URL furl = res.getFinalUrl();
    if (furl == null) {
        furl = req.url;//from   w  w  w .  j  a v  a 2  s  .  c  o  m
    }

    BrowserCompatSpecFactory bcsf = new BrowserCompatSpecFactory();
    CookieSpec cspec = bcsf.newInstance(null);
    String protocol = furl.getProtocol();
    boolean issecure = ("https".equals(protocol));
    int port = furl.getPort();
    if (port == -1)
        port = 80;
    CookieOrigin origin = new CookieOrigin(furl.getHost(), port, furl.getPath(), issecure);

    Context ctx = Context.getCurrentContext();
    Scriptable out = ctx.newObject(_scope);
    Scriptable headers = ctx.newObject(_scope);
    Scriptable cookies = ctx.newObject(_scope);

    out.put("status", out, res.getResponseCode());

    String response_body = null;

    try {
        response_body = new String(res.getContent(), getResponseEncoding(res));
        out.put("body", out, response_body);
    } catch (java.io.UnsupportedEncodingException e) {
        throw new RuntimeException(e);
    }

    out.put("headers", out, headers);
    out.put("cookies", out, cookies);

    StringBuilder response_header_log = new StringBuilder();
    for (HTTPHeader h : res.getHeaders()) {
        if (h.getName().equalsIgnoreCase("set-cookie")) {
            String set_cookie = h.getValue();
            Matcher m = Pattern.compile("\\s*(([^,]|(,\\s*\\d))+)").matcher(set_cookie);
            while (m.find()) {
                Header ch = new BasicHeader("Set-Cookie", set_cookie.substring(m.start(), m.end()));
                try {
                    List<Cookie> pcookies = cspec.parse(ch, origin);
                    for (Cookie c : pcookies) {
                        cookies.put(c.getName(), cookies, new AcreCookie(c).toJsObject(_scope));
                    }
                } catch (MalformedCookieException e) {
                    // we've occasionally choked on cookie-set,
                    // e.g. www.google.com returning expires=; expires=Mon, 01-Jan-1990 00:00:00 GMT;
                    // no solution but at least log exactly what's happening.
                    String cookiestring = ch.toString();
                    _logger.warn("urlfetch.response.async", "exception thrown on bad cookie " + cookiestring);
                    throw new RuntimeException(e);
                }
            }
        }

        headers.put(h.getName(), headers, h.getValue());
        response_header_log.append(h.getName() + ": " + h.getValue() + ", ");
    }

    boolean system = req.system;
    boolean log_to_user = req.log_to_user;

    String log_body = new String();
    if (res.getResponseCode() != 200 && response_body != null) {
        log_body = response_body;
    }

    _logger.syslog4j("INFO", "urlfetch.response.async", "URL", furl.toString(), "Status",
            Integer.toString(res.getResponseCode()), "Headers", response_header_log, "Body", log_body);

    if (system && log_to_user) {
        _response.userlog4j("INFO", "urlfetch.response.async", "URL", furl.toString(), "Status",
                Integer.toString(res.getResponseCode()), "Headers", response_header_log);
    }

    _costCollector.collect((system) ? "asuc" : "auuc").collect((system) ? "asuw" : "auuw", waiting_time);

    return out;
}

From source file:com.mgmtp.jfunk.web.CapabilitiesProvider.java

@Override
public Map<String, DesiredCapabilities> get() {
    Configuration config = configProvider.get();

    Map<String, Map<String, List<JFunkCapability>>> capabilitiesMap = newHashMap();
    for (Entry<String, String> entry : config.entrySet()) {
        String key = entry.getKey();
        Matcher matcher = CAPABILITIES_PREFIX_PATTERN.matcher(key);
        if (matcher.find()) {
            String driverType = matcher.groupCount() == 1 && matcher.group(1) != null ? matcher.group(1)
                    : "global";
            String capabilityString = key.substring(matcher.end() + 1);
            int lastDotIndex = capabilityString.lastIndexOf('.');
            String value = entry.getValue();

            JFunkCapability capability;//  w  ww  . j  a v a2 s .c  om
            if (lastDotIndex != -1) {
                JFunkCapabilityType type = JFunkCapabilityType.LIST;
                try {
                    Integer.parseInt(capabilityString.substring(lastDotIndex + 1));
                    capabilityString = capabilityString.substring(0, lastDotIndex);
                } catch (NumberFormatException ex) {
                    // not a list capability
                    type = JFunkCapabilityType.STRING;
                }
                capability = new JFunkCapability(capabilityString, value, type);
            } else {
                capability = new JFunkCapability(capabilityString, value, JFunkCapabilityType.STRING);
            }

            Map<String, List<JFunkCapability>> map = capabilitiesMap.get(driverType);
            if (map == null) {
                map = newHashMapWithExpectedSize(5);
                capabilitiesMap.put(driverType, map);
            }
            List<JFunkCapability> list = map.get(capability.name);
            if (list == null) {
                list = newArrayListWithExpectedSize(1);
                map.put(capability.name, list);
            }
            list.add(capability);
        }
    }

    Map<String, List<JFunkCapability>> tmpGlobals = capabilitiesMap.remove("global");
    final Map<String, Object> globalCapabilities = tmpGlobals == null ? ImmutableMap.<String, Object>of()
            : transformCapabilities(tmpGlobals);

    final Proxy proxy = createProxyFromConfig(config);

    // transform in to map of capabilities for each webdriver type
    final Map<String, DesiredCapabilities> byDriverTypeCapabilities = transformEntries(capabilitiesMap,
            new EntryTransformer<String, Map<String, List<JFunkCapability>>, DesiredCapabilities>() {
                @Override
                public DesiredCapabilities transformEntry(final String key,
                        final Map<String, List<JFunkCapability>> value) {
                    Map<String, Object> capabilities = newHashMap(globalCapabilities);
                    Map<String, Object> transformedCapabilities = transformCapabilities(value);
                    capabilities.putAll(transformedCapabilities);

                    DesiredCapabilities result = new DesiredCapabilities(capabilities);
                    if (proxy != null) {
                        result.setCapability(CapabilityType.PROXY, proxy);
                    }
                    return result;
                }
            });

    // wrap, so we get empty capabilities instead of nulls
    return new ForwardingMap<String, DesiredCapabilities>() {
        @Override
        protected Map<String, DesiredCapabilities> delegate() {
            return byDriverTypeCapabilities;
        }

        @Override
        public DesiredCapabilities get(final Object key) {
            DesiredCapabilities capabilities = super.get(key);
            if (capabilities == null) {
                DesiredCapabilities desiredCapabilities = new DesiredCapabilities();
                if (proxy != null) {
                    desiredCapabilities.setCapability(CapabilityType.PROXY, proxy);
                }
                capabilities = desiredCapabilities;
            }
            return capabilities;
        }
    };
}