Example usage for java.util.regex MatchResult group

List of usage examples for java.util.regex MatchResult group

Introduction

In this page you can find the example usage for java.util.regex MatchResult group.

Prototype

public String group();

Source Link

Document

Returns the input subsequence matched by the previous match.

Usage

From source file:org.springframework.social.twitter.api.impl.TweetDeserializer.java

private void extractTickerSymbolEntitiesFromText(String text, Entities entities) {
    Pattern pattern = Pattern.compile("\\$[A-Za-z]+");
    Matcher matcher = pattern.matcher(text);
    while (matcher.find()) {
        MatchResult matchResult = matcher.toMatchResult();
        String tickerSymbol = matchResult.group().substring(1);
        String url = "https://twitter.com/search?q=%24" + tickerSymbol + "&src=ctag";
        entities.getTickerSymbols().add(new TickerSymbolEntity(tickerSymbol, url,
                new int[] { matchResult.start(), matchResult.end() }));
    }/*from w  w  w.  j  a v a  2 s  . c o  m*/
}

From source file:com.edgenius.wiki.render.filter.UserFilter.java

@Override
public void replace(StringBuffer buffer, MatchResult result, RenderContext context) {
    if (context.getCurrentRegion() == null) {
        AuditLogger.error("Unexpected case: Immutable fitler cannot find out current region." + result.group());
    }// w w w.  j  av  a  2s.c  om

    String content = context.getCurrentRegion() != null ? context.getCurrentRegion().getContent()
            : result.group(2);
    String username = content;

    StringBuffer sb = new StringBuffer(result.group(1));

    if (!StringUtils.isBlank(username)) {
        HashMap<String, String> attValues = new HashMap<String, String>();
        username = username.trim();

        attValues.put(NameConstants.NAME, username);

        //this image scr will be handler after all page finish scan to HTML
        ObjectPosition userPos = new ObjectPosition(result.group(0));
        userPos.uuid = context.createUniqueKey(false);
        userPos.serverHandler = HANDLER;
        userPos.values = attValues;
        context.getObjectList().add(userPos);
        sb.append(userPos.uuid);

        buffer.append(sb);

        //append tailed text after filter
        if (result.groupCount() > 2)
            buffer.append(result.group(3));
    } else {
        //if only "@@" in page, do nothing
        buffer.append(result.group(0));
    }

}

From source file:net.osten.watermap.convert.AZTReport.java

private WaterReport parseDataLine(String line) {
    WaterReport result = new WaterReport();

    try {// w  ww . j  a  va 2 s .  c  o m
        // Example line:
        // 8.3 8.3 Tub Spring (aka Bathtub Spring) spring 3 full tub; good trickle3/28/15 3/28/15 Bird Food 4/5/15

        // Mileages = first two decimals
        MatchResult decimalsMatch = RegexUtils.matchFirstOccurance(line, decimalPattern);
        if (decimalsMatch == null) {
            log.fine("Mileages not found");
            return null;
        }
        int decimalsEnd = decimalsMatch.end();

        // Type = spring | creek | spring fed | windmill | store | dirt tank | pipe | Town | etc..
        MatchResult typeMatch = RegexUtils.matchFirstOccurance(line, typesPattern);
        if (typeMatch == null) {
            log.fine("Type not found");
            return null;
        }
        log.finer("type=" + typeMatch.group());
        int typeEnd = typeMatch.end();

        // Name = text from second decimal number to type (spring,creek,etc.)
        log.finer("decimalsEnd=" + decimalsEnd + " typeEnd=" + typeEnd);
        String name = line.substring(decimalsEnd, typeEnd);
        result.setName(name.trim());

        // Historic Reliability = int after Type (can be "1 to 2" or "0-2")
        MatchResult histRelMatch = RegexUtils.matchFirstOccurance(line, histRelPattern3, typeEnd);
        if (histRelMatch == null) {
            histRelMatch = RegexUtils.matchFirstOccurance(line, histRelPattern2, typeEnd);
            if (histRelMatch == null) {
                histRelMatch = RegexUtils.matchFirstOccurance(line, histRelPattern1, typeEnd);
                if (histRelMatch == null) {
                    log.fine("Historical Reliability not found");
                    return null;
                }
            }
        }
        log.finer("histRel=" + histRelMatch.group());
        String historicReliability = mapHistoricReliability(histRelMatch.group().trim());
        int histRelEnd = histRelMatch.end();

        // Report Date = second date from right
        int reportDateEnd = -1;
        int reportDateStart = -1;
        List<MatchResult> dates = RegexUtils.matchOccurences(line, datePattern);
        if (dates.size() >= 2) {
            reportDateEnd = dates.get(dates.size() - 2).end();
            reportDateStart = dates.get(dates.size() - 2).start();
        } else {
            log.fine("Only found " + dates.size() + " dates");
            reportDateStart = Math.max(line.length() - 1, histRelEnd);
        }

        // Report = Historic Reliability to Report Date
        log.finer("histRelEnd=" + histRelEnd + " reportDateStart=" + reportDateStart);
        if (histRelEnd >= 0 && reportDateStart >= 0 && reportDateStart >= histRelEnd) {
            String report = line.substring(histRelEnd, reportDateStart);
            result.setDescription(report.trim() + "<br />Historical Reliability:" + historicReliability);
        } else {
            log.fine("cannot find historic reliability");
        }

        // Post Date = first date from right
        int postDateStart = -1;
        MatchResult postDate = RegexUtils.matchLastOccurence(line, datePattern);
        if (postDate == null) {
            log.fine("Post Date not found");
        } else {
            result.setLastReport(dateFormatter.parse(postDate.group()));
            postDateStart = postDate.start();
            log.finer("postDate=" + postDate.group());
        }

        // Reported By = text between Report Date and Post Date
        if (postDateStart >= 0 && reportDateEnd >= 0 && postDateStart > reportDateEnd) {
            String reportedBy = line.substring(reportDateEnd, postDateStart);
            log.finer("reportedBy=" + reportedBy);
        } else {
            log.finer("cannot find reportedBy");
        }

        result.setState(WaterStateParser.parseState(result.getDescription()));
        result.setSource(SOURCE_TITLE);
        result.setUrl(SOURCE_URL);
    } catch (

    ParseException e)

    {
        log.fine("ParseException:" + e.getLocalizedMessage());
    }

    return result;

}

From source file:com.edgenius.wiki.render.filter.LinkFilter.java

/**
 * @param result//  www .ja  v a 2 s . co  m
 * @param bodyRegion
 * @return
 */
protected LinkModel getLinkModel(MatchResult result, Region bodyRegion) {
    String full;
    if (bodyRegion != null) {
        full = bodyRegion.getContent();
    } else {
        AuditLogger.error("Unexpected case: Immutable fitler cannot find out current region." + result.group());
        full = result.group(1);
    }

    LinkModel model = LinkUtil.parseMarkup(full);
    return model;
}

From source file:com.edgenius.wiki.render.filter.ImageFilter.java

@Override
public void replace(StringBuffer buffer, MatchResult result, RenderContext context) {
    String src;/*from  ww w .  j  a v  a 2  s  .  com*/
    Region bodyRegion = context.getCurrentRegion();
    if (bodyRegion != null) {
        src = bodyRegion.getContent();
    } else {
        AuditLogger.error("Unexpected case: Immutable fitler cannot find out current region." + result.group());
        src = result.group(1);
    }

    HashMap<String, String> attValues = new HashMap<String, String>();
    //append leading text before the real markup !image.png!
    StringBuffer sb = new StringBuffer(result.group(1));

    if (src != null && src.trim().length() > 0) {
        src = src.trim();

        //there are some other attributes, such as float
        String[] split = StringUtil.splitWithoutEscaped(src, "|");
        //as splitwidhtouEscaped() always return non-zero length String[], 
        //ie, if there is "|" then return input string as first element of string[], so it is safe to check split[0]
        src = split[0];

        for (int idx = 1; idx < split.length; idx++) {
            String att = split[idx].trim();
            if (SharedConstants.ALIGN_VALUES.contains(att)) {
                attValues.put(ALIGN, att);
            } else if (SharedConstants.SIZE_VALUES.contains(att)) {
                if (StringUtil.equalsIgnoreCase(SharedConstants.SIZE_VALUES.big.getName(), att)
                        || StringUtil.equalsIgnoreCase(SharedConstants.SIZE_VALUES.large.getName(), att)) {
                    // large thumbnail
                    attValues.put(WIDTH, ImageModel.LARGE_THUMBNAIL_WIDTH);
                } else {
                    // small thumbnail
                    attValues.put(WIDTH, ImageModel.SMALL_THUMBNAIL_WIDTH);
                }
            } else {
                if (att.indexOf("=") != -1) {
                    String[] pair = att.split("=");
                    if (pair.length == 2) {
                        attValues.put(pair[0], EscapeUtil.removeSlashEscape(pair[1]));
                    }
                } else {
                    //is it xxx * yyy ?
                    String[] wh = att.split("\\*");
                    if (wh.length == 2) {
                        int w = NumberUtils.toInt(wh[0], -1);
                        int h = NumberUtils.toInt(wh[1], -1);
                        if (w != -1 && h != -1) {
                            attValues.put(WIDTH, "" + w);
                            attValues.put(HEIGHT, "" + h);
                        }
                    }
                }
            }
        }

        attValues.put(SRC, src);
        //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        // NOTE: always user ImageHandler rather that simple append "http://image-file-url" 
        // after buffer. The reason is image file name may be any, for example, my--pic--1.jpg,
        // if append to buffer, file name will replace by StrightThrough filter! 
        ObjectPosition pos = new ObjectPosition(result.group(0));
        pos.uuid = context.createUniqueKey(false);
        pos.serverHandler = HANDLER;
        pos.values = attValues;
        context.getObjectList().add(pos);
        sb.append(pos.uuid);
        buffer.append(sb);

        if (bodyRegion != null && bodyRegion.getSubRegion() != null && pos != null) {
            bodyRegion.getSubRegion().setKey(pos.uuid);
        }

        //append tailed text after markup
        if (result.groupCount() > 2)
            buffer.append(result.group(3));
        return;
    } else {
        //TODO need i18n
        buffer.append(RenderUtil.renderError("Image filter needs src attribute to declare the image URL.",
                result.group(0)));
    }
}

From source file:org.openhab.binding.lutron.handler.IPBridgeHandler.java

private boolean login(IPBridgeConfig config) throws IOException, InterruptedException {
    this.session.open(config.getIpAddress());

    this.session.waitFor("login:");
    this.session.writeLine(config.getUser());
    this.session.waitFor("password:");
    this.session.writeLine(config.getPassword());

    MatchResult matchResult = this.session.waitFor("(login:|GNET>)");

    return "GNET>".equals(matchResult.group());
}

From source file:org.openhab.binding.lutron.internal.handler.IPBridgeHandler.java

private boolean login(IPBridgeConfig config) throws IOException, InterruptedException, LutronSafemodeException {
    this.session.open(config.getIpAddress());
    this.session.waitFor("login:");

    // Sometimes the Lutron Smart Bridge Pro will request login more than once.
    for (int attempt = 0; attempt < MAX_LOGIN_ATTEMPTS; attempt++) {
        this.session.writeLine(config.getUser() != null ? config.getUser() : DEFAULT_USER);
        this.session.waitFor("password:");
        this.session.writeLine(config.getPassword() != null ? config.getPassword() : DEFAULT_PASSWORD);

        MatchResult matchResult = this.session.waitFor(LOGIN_MATCH_REGEX);

        if (PROMPT_GNET.equals(matchResult.group()) || PROMPT_QNET.equals(matchResult.group())) {
            return true;
        } else if (PROMPT_SAFE.equals(matchResult.group())) {
            logger.warn("Lutron repeater is in safe mode. Unable to connect.");
            throw new LutronSafemodeException("Lutron repeater in safe mode");
        }/*from w w  w .j a  v  a 2  s. com*/

        else {
            logger.debug("got another login prompt, logging in again");
            // we already got the login prompt so go straight to sending user
        }
    }
    return false;
}

From source file:org.openhab.binding.webbrick.handler.IPBridgeHandler.java

private boolean login(WebBrickBridgeConfig config) throws IOException, InterruptedException {
    this.session.open(config.getIpAddress());

    // this.session.waitFor("login:");
    // this.session.writeLine(config.getUser());
    // this.session.waitFor("password:");
    // this.session.writeLine(config.getPassword());
    ////from w  ww  .  j a  v a 2  s.  c o  m
    MatchResult matchResult = this.session.waitFor("(login:|GNET>)");

    return "GNET>".equals(matchResult.group());
}

From source file:org.segrada.servlet.SegradaSimplePageCachingFilter.java

/**
 * calculate key for page from httpRequest
 * @param httpRequest the request// www  .  j  a va  2 s . c  o m
 * @return cache key
 */
protected String calculateKey(HttpServletRequest httpRequest) {
    HttpSession session = httpRequest.getSession();

    // get language from session
    Object lObject = session.getAttribute("language");
    String language = lObject == null ? null : (String) lObject;
    if (language == null)
        language = httpRequest.getLocale().getLanguage();

    // get url, context path stripped
    String urlPart = httpRequest.getRequestURI().substring(httpRequest.getContextPath().length());

    // filter out jsessionid URL addition, just in case - should not happen, because it is not clean, but nevertheless
    urlPart = jSessionFilter.matcher(urlPart).replaceFirst(""); //TODO: might be faster to use lastIndexOf and substr to replace this instead of regex

    // query data map - later to be sorted into a key
    SortedMap<String, String> queryData = new TreeMap<>();

    // match with urls that require session key addition to cache in order to function properly?
    MatchResult matchResult = addSessionToCacheKey.matcher(urlPart).toMatchResult();
    if (((Matcher) matchResult).find()) {
        // this is the same as the session key
        String controller = matchResult.group().substring(1, 2).toUpperCase() + matchResult.group().substring(2)
                + "Service";
        // get session data
        Object controllerData = session.getAttribute(controller);

        // create sorted map
        if (controllerData != null && controllerData instanceof Map) {
            @SuppressWarnings("unchecked")
            Map<String, Object> d = (Map<String, Object>) controllerData;
            for (Map.Entry<String, Object> entry : d.entrySet()) {
                Object o = entry.getValue();
                String value;
                // concatenate string array in order to make caching work
                if (o instanceof String[])
                    value = String.join(",", (String[]) o);
                else // all other cases: convert to string
                    value = entry.getValue().toString();
                queryData.put(entry.getKey(), value);
            }
        }
    }

    // get query data and add it to list (overwrite session, if needed)
    boolean clearTags = false; // flag to check whether parameter clearTags was sent in form data
    boolean tagsSetByForm = false; // flag to check whether there has been a field tags in form data
    for (Map.Entry<String, String[]> parameter : httpRequest.getParameterMap().entrySet()) {
        String key = parameter.getKey();
        if (key.equals("clearTags")) {
            clearTags = true;
            continue; // do not add to parameters
        }
        if (key.equals("tags"))
            tagsSetByForm = true; // tags were in form data
        queryData.put(key, String.join(",", parameter.getValue()));
    }
    // did we have field clearTags in form, but no tags were set? => delete tags saved in session, if needed
    if (clearTags && !tagsSetByForm)
        queryData.remove("tags"); // will be removed from session via controller

    // create query string as key
    StringBuilder queryString = new StringBuilder();
    for (Map.Entry<String, String> entry : queryData.entrySet()) {
        try {
            String encodedName = URLEncoder.encode(entry.getKey(), "UTF-8");
            Object value = entry.getValue();
            String encodedValue = value != null ? URLEncoder.encode(String.valueOf(value), "UTF-8") : "";
            // do not include page=1
            if (encodedName.equals("page") && encodedValue.equals("1"))
                continue;
            if (queryString.length() > 0)
                queryString.append('&');
            queryString.append(encodedName).append('=').append(encodedValue);
        } catch (Exception e) {
            logger.warn("Could not encode field " + entry.getKey() + " with value " + entry.getValue(), e);
        }
    }

    // get session id - make session dependent
    Identity identity = injector.getInstance(Identity.class);
    String id;
    // not logged in/no session
    if (identity == null || !identity.isAuthenticated() || identity.getId() == null)
        id = "NOTLOGGEDIN";
    // admin view? all admins get the same view
    else if (identity.hasRole("ADMIN"))
        id = "ADMIN";
    // single user cache - might have access to certain elements only
    else
        id = identity.getId();

    // create key
    return httpRequest.getMethod() + language + urlPart + id + encode(queryString);
}