Example usage for java.util.regex Matcher replaceFirst

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

Introduction

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

Prototype

public String replaceFirst(Function<MatchResult, String> replacer) 

Source Link

Document

Replaces the first subsequence of the input sequence that matches the pattern with the result of applying the given replacer function to the match result of this matcher corresponding to that subsequence.

Usage

From source file:me.vertretungsplan.parser.ParserUtils.java

static List<String> handleUrlWithDateFormat(String url) {
    List<String> urls = new ArrayList<>();
    Pattern dateFormatPattern = Pattern.compile("\\{date\\(([^)]+)\\)\\}");
    Matcher matcher = dateFormatPattern.matcher(url);
    if (matcher.find()) {
        String pattern = matcher.group(1);
        for (int j = 0; j < 7; j++) {
            LocalDate date = LocalDate.now().plusDays(j);
            String dateStr = DateTimeFormat.forPattern(pattern).print(date);
            String urlWithDate = matcher.replaceFirst(dateStr);
            urls.add(urlWithDate);/*from   w  w w.  j  a  v a  2 s.co m*/
        }
    } else {
        urls.add(url);
    }
    return urls;
}

From source file:org.assertj.assertions.generator.util.ClassUtil.java

public static String getNegativePredicateFor(String name) {
    Matcher m = PREFIX_PATTERN.matcher(name);
    if (m.find()) {
        return m.replaceFirst(PREDICATE_PREFIXES.get(m.group()));
    }//from   ww  w  . ja v a  2  s . c om
    return null;
}

From source file:com.qrmedia.commons.persistence.hibernate.clone.HibernateEntityBeanCloner.java

private static Collection<String> getPropertyNames(Collection<Method> methods) {
    Collection<String> methodNames = new ArrayList<String>();

    /*//  w w w  .j a v  a  2  s.  com
     * If a method is an instance method, does not return void, takes no parameters 
     * and is named "get..." (it's assumed to be public), add the corresponding field name.
     */
    for (Method method : methods) {
        assert Modifier.isPublic(method.getModifiers()) : method;
        String methodName = method.getName();
        Matcher getterNameMatcher = GETTER_PREFIX.matcher(methodName);

        if (!Modifier.isStatic(method.getModifiers()) && (method.getReturnType() != Void.class)
                && (method.getParameterTypes().length == 0) && getterNameMatcher.matches()) {

            // the first group is the (uppercase) first letter of the field name
            methodNames.add(getterNameMatcher.replaceFirst(getterNameMatcher.group(1).toLowerCase() + "$2"));
        }

    }

    return methodNames;
}

From source file:org.dasein.cloud.terremark.Terremark.java

public static String removeCommas(String tag) {
    Pattern p = Pattern.compile("[, ]");
    Matcher m = p.matcher(tag);
    String clean = m.replaceFirst("");
    return clean;
}

From source file:org.loklak.harvester.YoutubeScraper.java

public static JSONObject parseVideo(final BufferedReader br) throws IOException {
    String input;// www.  j  ava 2  s. c o  m
    JSONObject json = new JSONObject(true);
    boolean parse_span = false, parse_license = false;
    String itemprop = "", itemtype = ""; // values for span
    while ((input = br.readLine()) != null)
        try {
            input = input.trim();
            //System.out.println(input); // uncomment temporary to debug or add new fields
            int p;

            if (parse_license) {
                if ((p = input.indexOf("<li")) >= 0) {
                    String tag = parseTag(input, p);
                    if (tag == null)
                        continue;
                    if (tag.startsWith("<a ")) {
                        tag = parseTag(tag, 0);
                        addRDF(new String[] { "youtube", "category", tag }, json);
                    } else {
                        addRDF(new String[] { "youtube", "license", tag }, json);
                    }
                    parse_license = false;
                    continue;
                }
            } else if (parse_span) {
                if ((p = input.indexOf("itemprop=\"")) >= 0) {
                    String[] token = parseItemprop(input, p, new String[] { "href", "content" }, "");
                    if (token == null)
                        continue;
                    int q = itemtype.indexOf("//");
                    if (q < 0)
                        continue;
                    String subject = itemtype.substring(q + 2).replace('.', '_').replace('/', '_');
                    String predicate = itemprop + "_" + token[1];
                    String object = token[2];
                    addRDF(new String[] { subject, predicate, object }, json);
                    continue;
                }
                if (input.indexOf("</span>") >= 0) {
                    parse_span = false;
                    continue;
                }
            } else {
                tags: for (String tag : html_tags) {
                    if ((p = input.indexOf("<" + tag)) >= 0) {
                        addRDF(new String[] { "html", tag, parseTag(input, p) }, json);
                        continue tags;
                    }
                }
                vocs: for (String subject : microformat_vocabularies) {
                    if ((p = input.indexOf("property=\"" + subject + ":")) >= 0) {
                        addRDF(parseMicroformat(input, "property", p), json);
                        continue vocs;
                    }
                    if ((p = input.indexOf("name=\"" + subject + ":")) >= 0) {
                        addRDF(parseMicroformat(input, "name", p), json);
                        continue vocs;
                    }
                }
                if ((p = input.indexOf("span itemprop=\"")) >= 0) {
                    String[] token = parseItemprop(input, p, new String[] { "itemtype" }, "");
                    if (token == null)
                        continue;
                    itemprop = token[1];
                    itemtype = token[2];
                    parse_span = true;
                    continue;
                }
                if ((p = input.indexOf("itemprop=\"")) >= 0) {
                    String[] token = parseItemprop(input, p, new String[] { "content" }, "youtube");
                    if (token == null)
                        continue;
                    addRDF(token, json);
                    continue;
                }
                if ((p = input.indexOf("class=\"content watch-info-tag-list")) >= 0) {
                    parse_license = true;
                    continue;
                }
                if ((p = input.indexOf("yt-subscriber-count")) >= 0) {
                    String subscriber_string = parseProp(input, p, "title");
                    if (subscriber_string == null)
                        continue;
                    json.put("youtube_subscriber", parseNumber(subscriber_string));
                    continue;
                }
                if (input.indexOf("\"like this") > 0 && (p = input.indexOf("yt-uix-button-content")) >= 0) {
                    String likes_string = parseTag(input, p);
                    json.put("youtube_likes", parseNumber(likes_string));
                    continue;
                }
                if (input.indexOf("\"dislike this") > 0 && (p = input.indexOf("yt-uix-button-content")) >= 0) {
                    String dislikes_string = parseTag(input, p);
                    json.put("youtube_dislikes", parseNumber(dislikes_string));
                    continue;
                }
                if ((p = input.indexOf("watch-view-count")) >= 0) {
                    String viewcount_string = parseTag(input, p);
                    if (viewcount_string == null)
                        continue;
                    viewcount_string = viewcount_string.replace(" views", "");
                    if (viewcount_string.length() == 0)
                        continue;
                    long viewcount = 0;
                    // if there are no views, there may be a string saying "No". But this is done in all languages, so we just catch a NumberFormatException
                    try {
                        viewcount = parseNumber(viewcount_string);
                    } catch (NumberFormatException e) {
                    }
                    json.put("youtube_viewcount", viewcount);
                    continue;
                }
                if ((p = input.indexOf("watch?v=")) >= 0) {
                    p += 8;
                    int q = input.indexOf("\"", p);
                    if (q > 0) {
                        String videoid = input.substring(p, q);
                        int r = videoid.indexOf('&');
                        if (r > 0)
                            videoid = videoid.substring(0, r);
                        addRDF(new String[] { "youtube", "next", videoid }, json);
                        continue;
                    }
                }
                if ((p = input.indexOf("playlist-header-content")) >= 0) {
                    String playlist_title = parseProp(input, p, "data-list-title");
                    if (playlist_title == null)
                        continue;
                    addRDF(new String[] { "youtube", "playlist_title", playlist_title }, json);
                    continue;
                }
                if ((p = input.indexOf("yt-uix-scroller-scroll-unit")) >= 0) {
                    String playlist_videoid = parseProp(input, p, "data-video-id");
                    if (playlist_videoid == null)
                        continue;
                    addRDF(new String[] { "youtube", "playlist_videoid", playlist_videoid }, json);
                    continue;
                }
                if ((p = input.indexOf("watch-description-text")) >= 0) {
                    p = input.indexOf('>', p);
                    int q = input.indexOf("</div", p);
                    String text = input.substring(p + 1, q < 0 ? input.length() : q);
                    text = paragraph.matcher(brend.matcher(text).replaceAll("\n")).replaceAll("").trim();
                    Matcher m;
                    anchor_loop: while ((m = anchor_pattern.matcher(text)).find())
                        try {
                            text = m.replaceFirst(m.group(1) + " ");
                        } catch (IllegalArgumentException e) {
                            text = "";
                            break anchor_loop;
                        }
                    text = CharacterCoding.html2unicode(text);
                    json.put("youtube_description", text);
                    continue;
                }
            }
        } catch (Throwable e) {
            e.printStackTrace();
            System.err.println("error in video " + json.toString(2));
            System.err.println("current line: " + input);
            System.exit(0);
        }
    br.close();
    return json;
}

From source file:org.apache.camel.component.restlet.RestletProducer.java

private static String buildUri(RestletEndpoint endpoint, Exchange exchange) throws CamelExchangeException {
    String uri = endpoint.getProtocol() + "://" + endpoint.getHost() + ":" + endpoint.getPort()
            + endpoint.getUriPattern();/*ww  w .  j  ava 2 s .  com*/

    // substitute { } placeholders in uri and use mandatory headers
    if (LOG.isTraceEnabled()) {
        LOG.trace("Substituting { } placeholders in uri: " + uri);
    }
    Matcher matcher = PATTERN.matcher(uri);
    while (matcher.find()) {
        String key = matcher.group(1);
        String header = exchange.getIn().getHeader(key, String.class);
        // header should be mandatory
        if (header == null) {
            throw new CamelExchangeException("Header with key: " + key + " not found in Exchange", exchange);
        }

        if (LOG.isTraceEnabled()) {
            LOG.trace("Replacing: " + matcher.group(0) + " with header value: " + header);
        }

        uri = matcher.replaceFirst(header);
        // we replaced uri so reset and go again
        matcher.reset(uri);
    }

    if (LOG.isDebugEnabled()) {
        LOG.debug("Using uri: " + uri);
    }

    return uri;
}

From source file:org.squale.squalix.configurationmanager.ConfigUtility.java

/**
 * This method parses the given String to replace any "${...}"-like variable by the corresponding system property.
 * If no property is found, then the variable is left as is.
 * //from   w w  w  .java  2 s  .  c  o m
 * @param originalString the string to filter
 * @return the filtered String
 */
public static String filterStringWithSystemProps(String originalString) {
    String result = originalString;

    // Defines a "${...}"-like variable
    Pattern pattern = Pattern.compile("\\$\\{(\\w||\\.)*\\}");
    Matcher matcher = pattern.matcher(result);
    // try to find occurrences
    int searchIndex = 0;
    while (matcher.find(searchIndex)) {
        String propVar = matcher.group();
        // retrieve the name of the variable
        String propName = matcher.group().substring(2, propVar.length() - 1);
        // and try to retrieve its value
        String propValue = System.getProperty(propName);
        if (propValue != null) {
            // need to quote the string to prevent "\" to be removed
            result = matcher.replaceFirst(Matcher.quoteReplacement(propValue));
            searchIndex = matcher.start() + propValue.length();
        } else {
            // do nothing but increase the search index
            searchIndex = matcher.end();
        }
        // keep on analyzing the string for other matches
        matcher = pattern.matcher(result);
    }

    return result;
}

From source file:net.wastl.webmail.misc.Helper.java

public static String decryptTEA(String src) {
    StringTokenizer tok = new StringTokenizer(src, ": ");
    byte[] key = new BigInteger(str_key, 16).toByteArray();
    TEA tea = new TEA(key);
    byte inb[] = new byte[tok.countTokens()];
    for (int i = 0; i < inb.length && tok.hasMoreTokens(); i++) {
        String s = tok.nextToken();
        try {//  w ww. ja v  a2 s  . co  m
            inb[i] = (byte) (Integer.parseInt(s, 16) - 128);
        } catch (NumberFormatException ex) {
            throw new NumberFormatException("Could not convert string '" + s + "' to byte.");
        }
    }
    byte dec[] = tea.decode(inb, inb.length);
    String s = new String(dec);
    // log.debug("encryptTEA: Returning "+s);
    java.util.regex.Matcher m = nonGraphPattern.matcher(s);
    if (!m.find())
        return s;
    log.warn("Executed work-around for TEA decryption bug");
    String fixedS = m.replaceFirst("");
    if (s.equals(fixedS))
        log.warn("The TEA work-around was not needed in this case");
    // I believe the rot of the bug is with padding in the TEA.decode()
    // method(s).  I do not have time to fix the real problem there.
    return fixedS;
}

From source file:gsn.http.ac.ParameterSet.java

private static void changeSensorName(String filepath, String name) {
    File f = new File(filepath);

    Pattern pat = Pattern.compile("name[\\s]*=[\\s]*\"[\\s]*[\\S]+[\\s]*\"");
    Matcher match;
    FileInputStream fs = null;/*from  www.j  a v a2  s  . co m*/
    InputStreamReader in = null;
    BufferedReader br = null;

    StringBuffer sb = new StringBuffer();
    String textinLine;

    try {
        fs = new FileInputStream(f);
        in = new InputStreamReader(fs);
        br = new BufferedReader(in);

        while (true) {
            textinLine = br.readLine();
            if (textinLine == null)
                break;
            if (textinLine.contains("<virtual-sensor")) {
                match = pat.matcher(textinLine);
                match.find();
                textinLine = match.replaceFirst("name=\"" + name + "\"");
            }
            sb.append(textinLine + "\n");
        }
        fs.close();
        in.close();
        br.close();
    } catch (FileNotFoundException e) {
        logger.error(e.getMessage(), e);
    } catch (IOException e) {
        logger.error(e.getMessage(), e);
    }

    try {
        FileWriter fstream = new FileWriter(f); // write file again
        BufferedWriter outobj = new BufferedWriter(fstream);
        outobj.write(sb.toString());
        outobj.close();

    } catch (Exception e) {
        logger.error(e.getMessage(), e);
    }
}

From source file:org.openiot.gsn.http.ac.ParameterSet.java

private static void changeSensorName(String filepath, String name) {
    File f = new File(filepath);

    Pattern pat = Pattern.compile("name[\\s]*=[\\s]*\"[\\s]*[\\S]+[\\s]*\"");
    Matcher match;
    FileInputStream fs = null;//  w ww  .  ja  v a2s .  c  om
    InputStreamReader in = null;
    BufferedReader br = null;

    StringBuffer sb = new StringBuffer();
    String textinLine;

    try {
        fs = new FileInputStream(f);
        in = new InputStreamReader(fs);
        br = new BufferedReader(in);

        while (true) {
            textinLine = br.readLine();
            if (textinLine == null)
                break;
            if (textinLine.contains("<virtual-sensor")) {
                match = pat.matcher(textinLine);
                match.find();
                textinLine = match.replaceFirst("name=\"" + name + "\"");
            }
            sb.append(textinLine + "\n");
        }
        fs.close();
        in.close();
        br.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    try {
        FileWriter fstream = new FileWriter(f); // write file again
        BufferedWriter outobj = new BufferedWriter(fstream);
        outobj.write(sb.toString());
        outobj.close();

    } catch (Exception e) {
        System.err.println("Error: " + e.getMessage());
    }
}