Example usage for java.util.regex Matcher appendReplacement

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

Introduction

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

Prototype

public Matcher appendReplacement(StringBuilder sb, String replacement) 

Source Link

Document

Implements a non-terminal append-and-replace step.

Usage

From source file:uk.ac.ox.oucs.vle.XcriOxCapPopulatorImpl.java

/**
 *  * Processing of descriptivetext fields where descriptiveTextType.isXhtml=false
 * /*from  w w w.  jav a  2s  . c  o m*/
 * @param data
 * @return
 */
static String parse(String data) {

    data = data.replaceAll("<", "&lt;");
    data = data.replaceAll(">", "&gt;");
    data = FormattedText.convertPlaintextToFormattedText(data);

    Pattern pattern = Pattern.compile("[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,4}", Pattern.CASE_INSENSITIVE);
    Matcher matcher = pattern.matcher(data);

    StringBuffer sb = new StringBuffer(data.length());
    while (matcher.find()) {
        String text = matcher.group(0);
        matcher.appendReplacement(sb, "<a class=\"email\" href=\"mailto:" + text + "\">" + text + "</a>");
    }
    matcher.appendTail(sb);

    pattern = Pattern.compile("(https?|ftps?):\\/\\/[a-z_0-9\\\\\\-]+(\\.([\\w#!:?+=&%@!\\-\\/])+)+",
            Pattern.CASE_INSENSITIVE);
    matcher = pattern.matcher(sb.toString());

    sb = new StringBuffer(data.length());
    while (matcher.find()) {
        String text = matcher.group(0);
        matcher.appendReplacement(sb,
                "<a class=\"url\" href=\"" + text + "\" target=\"_blank\">" + text + "</a>");
    }
    matcher.appendTail(sb);
    return sb.toString();
}

From source file:com.blocks.framework.utils.date.StringUtil.java

/**
  * ????// w  w  w  . j a v a 2  s .c  om
  * 
  * @param src
  *            String
  * @param pattern
  *            String
  * @param to
  *            String
  * @return String
  */
 public static String replaceAll(String src, String pattern, String to) {
     if (src == null) {
         return null;
     }
     if (pattern == null) {
         return src;
     }

     StringBuffer sb = new StringBuffer();
     Pattern p = Pattern.compile(pattern);
     Matcher m = p.matcher(src);

     int i = 1;
     while (m.find()) {
         // System.out.println("" + i + "?:" + m.group() +
         // " ?:" + m.start() + "-" + (m.end() - 1));
         m.appendReplacement(sb, to);
         i++;
     }
     m.appendTail(sb);
     // System.out.println("??:" + sb);
     return sb.toString();
 }

From source file:com.gargoylesoftware.htmlunit.javascript.IEConditionalCompilationScriptPreProcessor.java

private String processSet(final String body) {
    final Matcher m = SET_PATTERN.matcher(body);
    final StringBuffer sb = new StringBuffer();
    while (m.find()) {
        setVariables_.add(m.group(1));/*w w w  .j  a v  a  2 s  .c om*/
        m.appendReplacement(sb, CC_VARIABLE_PREFIX + m.group(1).substring(1) + m.group(2) + ";");
    }
    m.appendTail(sb);
    return sb.toString();
}

From source file:edu.sdsc.scigraph.internal.CypherUtil.java

String entailRelationships(String cypher) {
    Matcher m = pattern.matcher(cypher);
    StringBuffer buffer = new StringBuffer();
    while (m.find()) {
        String group = m.group().substring(1, m.group().length() - 1);
        Set<String> parentTypes = newHashSet(Splitter.on('|').split(group));
        String entailedTypes = on('|').join(getEntailedRelationshipTypes(parentTypes));
        m.appendReplacement(buffer, ":" + entailedTypes);
    }/*from   w w  w .j  a va  2 s  .  c  o m*/
    m.appendTail(buffer);
    return buffer.toString();
}

From source file:org.lockss.util.UrlUtil.java

/** Remove a subdomain from the host part of a URL
 * @param url the URL string/*  w w w  .j  av  a2  s  .c  o m*/
 * @param subdomain the (case insensitive) subdomain to remove (no
 * trailing dot)
 * @return the URL string with the subdomain removed from the beginning
 * of the host
 */
public static String delSubDomain(String url, String subdomain) {
    Matcher m = SCHEME_HOST_PAT.matcher(url);
    if (m.find()) {
        String host = m.group(2);
        if (StringUtil.startsWithIgnoreCase(host, subdomain) && '.' == host.charAt(subdomain.length())) {
            StringBuffer sb = new StringBuffer();
            m.appendReplacement(sb, "$1" + host.substring(subdomain.length() + 1));
            m.appendTail(sb);
            return sb.toString();
        }
    }
    return url;
}

From source file:org.carewebframework.maven.plugin.theme.ZKThemeProcessor.java

/**
 * Adjust any color references using the active hue filter.
 * /* w w w  .j  av  a  2  s  .  com*/
 * @param line The string to modify
 * @return the modified string
 */
public String replaceColor(String line) {
    StringBuffer sb = new StringBuffer();
    Matcher matcher = COLOR_PATTERN.matcher(line);

    while (matcher.find()) {
        String hexColor = matcher.group(1);
        int rgb = hueFilter.filterRGB(0, 0, Integer.parseInt(hexColor, 16));
        String transfHexColor = String.format("%06x", rgb);
        matcher.appendReplacement(sb, "#" + transfHexColor);
    }

    matcher.appendTail(sb);
    return sb.toString();
}

From source file:org.echocat.jomon.resources.optimizing.CombineCssResourcesOptimizer.java

@Nonnull
protected String handleImports(@Nonnull String oldCssBody, @Nonnull OptimizationContext context)
        throws Exception {
    final Matcher matcher = IMPORT_PATTERN.matcher(oldCssBody);
    final StringBuffer sb = new StringBuffer();
    while (matcher.find()) {
        final String uri = matcher.group(3) != null ? matcher.group(3) : matcher.group(2);
        final String importedBody = getBodyOf(uri, context);
        final String newReplacement = quoteReplacement(importedBody);
        matcher.appendReplacement(sb, newReplacement);
    }//  w  w  w . j ava 2s  .  co m
    matcher.appendTail(sb);
    return sb.toString();
}

From source file:org.jbosson.plugins.amq.ArtemisMBeanDiscoveryComponent.java

private String substituteConfigProperties(String objectName, Configuration configuration, boolean isParent) {

    final Pattern p;
    if (isParent) {
        p = PROPERTY_NAME_PATTERN;//  w  w  w.  j  a v a2 s  .  c  o m
    } else {
        p = OBJECT_NAME_PROPERTY_PATTERN;
    }

    StringBuffer buffer = new StringBuffer();
    final Matcher m = p.matcher(objectName);
    while (m.find()) {
        String name = m.group(1);
        m.appendReplacement(buffer, configuration.getSimpleValue(name));
    }
    m.appendTail(buffer);
    return buffer.toString();
}

From source file:io.hops.hopsworks.api.jupyter.URITemplateProxyServlet.java

@Override
protected void service(HttpServletRequest servletRequest, HttpServletResponse servletResponse)
        throws ServletException, IOException {

    //First collect params
    /*/*from   w w w .j  ava2s  .  co  m*/
     * Do not use servletRequest.getParameter(arg) because that will
     * typically read and consume the servlet InputStream (where our
     * form data is stored for POST). We need the InputStream later on.
     * So we'll parse the query string ourselves. A side benefit is
     * we can keep the proxy parameters in the query string and not
     * have to add them to a URL encoded form attachment.
     */
    String queryString = "?" + servletRequest.getQueryString();//no "?" but might have "#"
    int hash = queryString.indexOf('#');
    if (hash >= 0) {
        queryString = queryString.substring(0, hash);
    }
    List<NameValuePair> pairs;
    try {
        //note: HttpClient 4.2 lets you parse the string without building the URI
        pairs = URLEncodedUtils.parse(new URI(queryString), "UTF-8");
    } catch (URISyntaxException e) {
        throw new ServletException("Unexpected URI parsing error on " + queryString, e);
    }
    LinkedHashMap<String, String> params = new LinkedHashMap<>();
    for (NameValuePair pair : pairs) {
        params.put(pair.getName(), pair.getValue());
    }

    //Now rewrite the URL
    StringBuffer urlBuf = new StringBuffer();//note: StringBuilder isn't supported by Matcher
    Matcher matcher = TEMPLATE_PATTERN.matcher(targetUriTemplate);
    while (matcher.find()) {
        String arg = matcher.group(1);
        String replacement = params.remove(arg);//note we remove
        if (replacement != null) {
            matcher.appendReplacement(urlBuf, replacement);
            port = replacement;
        } else if (port != null) {
            matcher.appendReplacement(urlBuf, port);
        } else {
            throw new ServletException("Missing HTTP parameter " + arg + " to fill the template");
        }
    }
    matcher.appendTail(urlBuf);
    String newTargetUri = urlBuf.toString();
    servletRequest.setAttribute(ATTR_TARGET_URI, newTargetUri);
    try {
        targetUriObj = new URI(newTargetUri);
    } catch (Exception e) {
        throw new ServletException("Rewritten targetUri is invalid: " + newTargetUri, e);
    }
    servletRequest.setAttribute(ATTR_TARGET_HOST, URIUtils.extractHost(targetUriObj));

    //Determine the new query string based on removing the used names
    StringBuilder newQueryBuf = new StringBuilder(queryString.length());
    for (Map.Entry<String, String> nameVal : params.entrySet()) {
        if (newQueryBuf.length() > 0) {
            newQueryBuf.append('&');
        }
        newQueryBuf.append(nameVal.getKey()).append('=');
        if (nameVal.getValue() != null) {
            newQueryBuf.append(nameVal.getValue());
        }
    }
    servletRequest.setAttribute(ATTR_QUERY_STRING, newQueryBuf.toString());

    // Create Exchange object with targetUriObj
    // create transport object
    //    ServiceProxy sp = new ServiceProxy();
    //    sp.setTargetUrl(ATTR_TARGET_URI);
    //    super.service(servletRequest, servletResponse);

    //              RouterUtil.initializeRoutersFromSpringWebContext(appCtx, config.
    //              getServletContext(), getProxiesXmlLocation(config));
}

From source file:org.fao.unredd.portal.Config.java

public String getLocalizedFileContents(File file, Locale locale) throws IOException, ConfigurationException {
    try {/*from  www  .  j a  va 2  s .  c om*/
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
        String template = IOUtils.toString(bis, "UTF-8");
        bis.close();
        Pattern patt = Pattern.compile("\\$\\{([\\w.]*)\\}");
        Matcher m = patt.matcher(template);
        StringBuffer sb = new StringBuffer(template.length());
        ResourceBundle messages = getMessages(locale);
        while (m.find()) {
            String text;
            try {
                text = messages.getString(m.group(1));
                m.appendReplacement(sb, text);
            } catch (MissingResourceException e) {
                // do not replace
            }
        }
        m.appendTail(sb);
        return sb.toString();
    } catch (UnsupportedEncodingException e) {
        logger.error("Unsupported encoding", e);
        return "";
    }
}