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:org.apache.ranger.plugin.conditionevaluator.RangerIpMatcher.java

String digestPolicyIp(final String policyIp) {
    if (LOG.isDebugEnabled()) {
        LOG.debug("==> RangerIpMatcher.digestPolicyIp(" + policyIp + ")");
    }/*from  w w w  . ja  v  a  2s  .  c o  m*/

    String result;
    Matcher matcher = allWildcards.matcher(policyIp);
    if (matcher.matches()) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("digestPolicyIp: policyIP[" + policyIp + "] all wildcards.");
        }
        result = "";
    } else if (policyIp.contains(".")) {
        matcher = trailingWildcardsIp4.matcher(policyIp);
        result = matcher.replaceFirst(".");
    } else {
        matcher = trailingWildcardsIp6.matcher(policyIp);
        // also lower cases the ipv6 items
        result = matcher.replaceFirst(":").toLowerCase();
    }

    if (LOG.isDebugEnabled()) {
        LOG.debug("<== RangerIpMatcher.digestPolicyIp(" + policyIp + "): " + policyIp);
    }
    return result;
}

From source file:org.apache.wiki.site.SiteGeneratorTest.java

/**
 * generates the content for a <em>regular</em> line. Initial blank space from ChangeLog is 
 * removed and JIRA id's are replaced by regular Markdown links and stored on the collection
 * of links./* w ww. ja va2  s .  c o m*/
 * 
 * @param line given line.
 * @param sb current content.
 * @param links collection of links, to be able to print JIRA links later on.
 */
void parseRegularLine(String line, StringBuilder sb, List<String> links) {
    line = StringUtils.replace(line, "       ", StringUtils.EMPTY);
    Matcher m = p.matcher(line);
    while (m.find()) {
        String replace = StringUtils.replace(m.group(0), "JSPWIKI-", "[JSPWIKI ");
        replace += "][JIRA-" + StringUtils.replace(m.group(0), "JSPWIKI-", StringUtils.EMPTY) + "]";
        links.add("JIRA-" + StringUtils.replace(m.group(0), "JSPWIKI-", StringUtils.EMPTY));
        line = m.replaceFirst(replace);
        m = p.matcher(line);
    }
    sb.append(line).append("\n");
}

From source file:sernet.gs.ui.rcp.main.CnAWorkspace.java

/**
 * Create a text file in the local file system from a resource (i.e. inside
 * a JAR file distributed with the application).
 *
 * Adapt line-feeds to local settings and optionally replace variables with
 * values given in a hashmap.//from w  ww  . j av a2  s.c  om
 *
 * Files are converted from charsetInfile to CHARSET_DEFAULT.
 *
 * @param infile
 *            relative path to a file accessed by a class loader
 * @param charsetInfile
 *            charset of input file Files are converted from charsetInfile
 *            to charsetOutfile
 * @param toDir
 *            path to directory of the created file
 * @param outfile
 *            name of created file
 * @param charsetOutfile
 *            charset of output file
 * @param variables
 *            property added to the file, may be null
 * @throws NullPointerException
 * @throws IOException
 */
protected void createTextFile(String infile, Charset charsetInfile, String toDir, String outfile,
        Charset charsetOutfile, Map<String, String> variables) throws NullPointerException, IOException {

    String infileResource = infile.replace('\\', '/');
    InputStream is = getClass().getClassLoader().getResourceAsStream(infileResource);
    InputStreamReader inRead = new InputStreamReader(is, charsetInfile);
    BufferedReader bufRead = new BufferedReader(inRead);
    StringBuffer skelFile = new StringBuffer();

    // write from skel file, replacing newline characters to system
    // specific:
    String line;
    Pattern var = Pattern.compile("\\{(.*)\\}"); //$NON-NLS-1$
    while ((line = bufRead.readLine()) != null) {
        line = line.replaceFirst("\n", LINE_SEP); //$NON-NLS-1$
        if (variables != null) {
            Matcher match = var.matcher(line);
            if (match.find()) {
                line = match.replaceFirst(variables.get(match.group(1)));
            }
        }
        skelFile.append(line + LINE_SEP);
    }
    bufRead.close();
    inRead.close();
    is.close();

    backupFile(toDir, outfile);
    FileOutputStream fout = new FileOutputStream(toDir + File.separator + outfile, false);
    OutputStreamWriter outWrite = new OutputStreamWriter(fout, charsetOutfile);
    outWrite.write(skelFile.toString());
    outWrite.close();
    fout.close();
}

From source file:net.zcarioca.zcommons.config.util.PropertiesBuilder.java

String getFilteredValue(String key) {
    String value = this.props.get(key);
    if (StringUtils.isEmpty(value)) {
        return "";
    }/*  w  ww. j a v  a2  s. co  m*/
    Matcher matcher = pattern.matcher(value);
    while (matcher.find()) {
        String grouping = matcher.group();
        String valKey = grouping.substring(2, grouping.length() - 1);

        String prop = getFilteredValue(valKey);
        if (!StringUtils.isEmpty(prop)) {
            value = matcher.replaceFirst(prop);
            matcher = pattern.matcher(value);
        }
    }
    return value;
}

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

public static String unshorten(String text) {
    while (true) {
        try {/*from   ww  w.ja  v  a2 s  .  c  o m*/
            Matcher m = emoji_pattern.matcher(text);
            if (m.find()) {
                String emoji = m.group(1);
                text = m.replaceFirst(emoji);
                continue;
            }
        } catch (Throwable e) {
            DAO.severe(e);
            break;
        }
        try {
            Matcher m = emoji_pattern_span.matcher(text);
            if (m.find()) {
                String emoji = m.group(1);
                text = m.replaceFirst(emoji);
                continue;
            }
        } catch (Throwable e) {
            DAO.severe(e);
            break;
        }
        try {
            Matcher m = hashtag_pattern.matcher(text);
            if (m.find()) {
                text = m.replaceFirst(" #" + m.group(1) + " "); // the extra spaces are needed because twitter removes them if the hashtag is followed with a link
                continue;
            }
        } catch (Throwable e) {
            DAO.severe(e);
            break;
        }
        try {
            Matcher m = timeline_link_pattern.matcher(text);
            if (m.find()) {
                String expanded = RedirectUnshortener.unShorten(m.group(2));
                text = m.replaceFirst(" " + expanded);
                continue;
            }
        } catch (Throwable e) {
            DAO.severe(e);
            break;
        }
        try {
            Matcher m = timeline_embed_pattern.matcher(text);
            if (m.find()) {
                text = m.replaceFirst("");
                continue;
            }
        } catch (Throwable e) {
            DAO.severe(e);
            break;
        }
        break;
    }
    text = cleanup_pattern.matcher(text).replaceAll("");
    text = MessageEntry.html2utf8(text);
    text = doublespace_pattern.matcher(text).replaceAll(" ");
    text = text.trim();
    return text;
}

From source file:GIST.IzbirkomExtractor.StreetNameNormalizer.java

/**
 * //  w  w w .  j  a v a2s .  c  o m
 * @param streetName street name to be normalized
 * @return normalized street name
 */
public ArrayList<String> normalize(String streetName) {

    /**
     * Array for street name variations.
     */
    ArrayList<String> variations = new ArrayList<String>();

    /* expand abbreviated street type, extract street type, and extract it from the street name */
    Matcher m = streetTypeAbbrList.getExpansionsPattern()
            .matcher(streetTypeAbbrList.expandAbbreviations(streetName.toLowerCase()));

    String streetType;
    String streetNoType;
    if (!m.find()) {
        logger.warning("No street type in " + streetName);
        streetType = "";
        streetNoType = streetName;
    } else {
        streetType = m.group(1);
        streetNoType = m.replaceFirst(" ");
    }
    streetNoType = streetNoType.replaceAll("\\s+", " ")
            .trim(); /* this is to fix case when street type is in the middle */
    streetNoType = WordUtils.capitalizeFully(streetNoType).replaceAll("\\b\\b",
            ""); /* capitalize word parts but avoid 
                   capitalizing single  */

    /* replacement from abbreviated street name parts */

    /* permute street type place in the street name */
    for (String streetNameVar : streetNamePartList.createAllExpansions(streetNoType)) {

        String[] streetNameParts = streetNameVar.split("\\s+");

        /* check each if each street name part is an ordinal */
        ArrayList<Ordinal> ordinals = new ArrayList<Ordinal>(streetNameParts.length);
        int ordinalCount = 0;
        for (int i = 0; i < streetNameParts.length; i++) {
            Ordinal o = ordinalFactory.parse(streetNameParts[i]);
            ordinals.add(o);
            if (o != null)
                ordinalCount++;
        }

        /* permute all parts of the street name except for street type */
        for (FischerKrause fk = new FischerKrause(streetNameParts.length); fk.hasNext();) {
            int idx[] = fk.next();

            StringBuilder sb = new StringBuilder();
            StringBuilder sb_regex = new StringBuilder(); /* StringBuilder for queries with regex */
            for (int i = 0; i < idx.length; i++) {
                sb.append(streetNameParts[idx[i]]);

                if (ordinals.get(idx[i]) != null)
                    sb_regex.append(ordinals.get(idx[i]).getSQLRegex());
                else
                    sb_regex.append(streetNameParts[idx[i]]);

                if (i == idx.length - 1)
                    continue; /* avoid adding space at the end of the string */

                sb.append(' ');
                sb_regex.append(' ');
            }

            /* permutation of the words without street types */
            variations.add(sb.toString() + ' ' + streetType);
            variations.add(streetType + ' ' + sb.toString());

            /* permutation for regexped form of the street name with ordinals regexps */
            if (ordinalCount > 0 && !sb.toString().contains(
                    "(")) { /* make sure that streetname itself does not contain regex-like symbols (typically resulting from parse errors) */
                variations.add("^" + sb_regex.toString() + ' ' + streetType + '$');
                variations.add("^" + streetType + ' ' + sb_regex.toString() + '$');

                /* if the street name starts with an ordinal add permutations with the street type after the 1st ordinal */
                if (ordinals.get(idx[0]) != null && streetNameParts.length > 1) {
                    variations
                            .add(sb.insert(streetNameParts[idx[0]].length() + 1, streetType + ' ').toString());
                    variations.add("^"
                            + sb_regex.insert(ordinals.get(idx[0]).getSQLRegex().length() + 1, streetType + ' ')
                                    .toString()
                            + '$');
                }
            }
        }
    }

    return variations;
}

From source file:org.cloudifysource.cloudformation.converter.api.CloudifyPrivateEc2TemplateConverter.java

String convertProperties(final List<ServiceProperties> properties, final String template) {
    String converted = template;// w  ww .  java2s  .c o m
    if (properties != null) {
        final Pattern p = Pattern.compile("\"#([\\w-_]+)#\"");
        Matcher m = p.matcher(converted);
        while (m.find()) {
            final String group1 = m.group(1);

            boolean foundProperties = false;
            for (final ServiceProperties serviceProperties : properties) {
                if (serviceProperties.getKey().equals(group1)) {
                    converted = m.replaceFirst("\"" + serviceProperties.getValue() + "\"");
                    m = p.matcher(converted);
                    foundProperties = true;
                    break;
                }
            }
            if (!foundProperties) {
                converted = m.replaceFirst(group1);
                m = p.matcher(converted);
            }
        }
    }
    return converted;
}

From source file:com.mirth.connect.manager.ManagerController.java

public void setServiceXmx(String xmx) {
    File file = new File(PlatformUI.MIRTH_PATH + ManagerConstants.PATH_SERVICE_VMOPTIONS);
    String contents = "";

    try {// ww w. j a va2  s. c o  m
        contents = FileUtils.readFileToString(file);
    } catch (IOException e) {
        // Ignore error if file does not exist
    }

    Pattern pattern = Pattern.compile("-Xmx(.*?)m");
    Matcher matcher = pattern.matcher(contents);

    if (matcher.find()) {
        contents = matcher.replaceFirst("-Xmx" + xmx + "m");
    } else if (xmx.length() != 0) {
        contents += "-Xmx" + xmx + "m";
    }

    try {
        FileUtils.writeStringToFile(file, contents);
    } catch (IOException e) {
        alertErrorDialog("Error writing file to: " + file.getPath());
    }
}

From source file:org.codehaus.enunciate.modules.rest.RESTContentTypeRoutingController.java

/**
 * Redirects the request to the location of the specific content type.
 *
 * @param request The request./*  w ww . j a va2  s  .  c  o  m*/
 * @param response The response.
 * @return null
 */
protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response)
        throws Exception {
    if (getContentTypeSupport() != null) {
        String requestContext = request.getRequestURI().substring(request.getContextPath().length());
        Matcher matcher = replacePattern.matcher(requestContext);
        if (matcher.find()) {
            List<String> contentTypes = getContentTypesByPreference(request);

            for (String contentType : contentTypes) {
                String contentTypeId = lookupContentTypeId(contentType);
                if (contentTypeId != null) {
                    String redirect = matcher
                            .replaceFirst("/" + URLEncoder.encode(contentTypeId, "UTF-8") + "/");
                    RequestDispatcher dispatcher = request.getRequestDispatcher(redirect);
                    if (dispatcher != null) {
                        try {
                            dispatcher.forward(request, response);
                        } catch (ServletException e) {
                            if (e.getRootCause() instanceof Exception) {
                                throw (Exception) e.getRootCause();
                            } else {
                                throw e;
                            }
                        }
                        return null;
                    }
                }
            }
        }
    }

    response.sendError(HttpServletResponse.SC_NOT_FOUND);
    return null;

}