Example usage for java.util.regex Matcher appendTail

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

Introduction

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

Prototype

public StringBuilder appendTail(StringBuilder sb) 

Source Link

Document

Implements a terminal append-and-replace step.

Usage

From source file:org.sejda.core.support.prefix.processor.NumberPrefixProcessor.java

/**
 * Try to find matches and replace them with the formatted number. An empty string is returned if no match is found.
 * /*w  w  w  . j a  v a  2 s  .  co m*/
 * @param inputString
 * @param num
 * @return the processed string if a match is found. An empty string if no match is found.
 */
protected String findAndReplace(String inputString, Integer num) {
    StringBuffer sb = new StringBuffer();
    Matcher m = Pattern.compile(findRegexp).matcher(inputString);
    while (m.find()) {
        String replacement = getReplacement(m.group(1), m.group(2), num);
        m.appendReplacement(sb, replacement);
    }
    m.appendTail(sb);
    return sb.toString();
}

From source file:cc.aileron.dao.db.sql.G2DaoSqlMapImpl.java

/**
 * @param targetClass//w w w.  ja v a 2 s  . c o  m
 * @return dir
 */
private String getDir(final Class<?> targetClass) {
    final String name = targetClass.getCanonicalName();
    if (name == null) {
        return null;
    }
    final StringBuffer buffer = new StringBuffer();
    final Matcher matcher = pattern.matcher(name);
    while (matcher.find()) {
        matcher.appendReplacement(buffer, "/" + matcher.group(1).toLowerCase());
    }
    return matcher.appendTail(buffer).toString();
}

From source file:net.triptech.metahive.CalculationParser.java

/**
 * Builds the calculation.//w ww .j a  va 2  s.  c  o  m
 *
 * @param calculation the calculation
 * @param values the values
 * @return the string
 */
public static String buildCalculation(String calculation, Map<Long, Double> values) {

    String parsedCalculation = "";

    logger.debug("Calculation: " + calculation);
    logger.debug("Values: " + values);

    if (StringUtils.isNotBlank(calculation) && values != null) {
        try {
            Pattern p = Pattern.compile(regEx);
            Matcher m = p.matcher(calculation);
            StringBuffer sb = new StringBuffer();
            logger.debug("Regular expression: " + regEx);
            while (m.find()) {
                logger.info("Variable instance found: " + m.group());
                try {
                    String text = m.group();
                    Long id = Long.parseLong(StringUtils.substring(text, 1));
                    logger.info("Variable id: " + id);

                    if (values.containsKey(id)) {
                        logger.debug("Contains variable " + id);
                        double value = values.get(id);
                        logger.debug("Value: " + value);
                        text = String.valueOf(value);
                    }
                    logger.debug("Replacement text: " + text);
                    m.appendReplacement(sb, Matcher.quoteReplacement(text));

                } catch (NumberFormatException nfe) {
                    logger.error("Error parsing variable id");
                }
            }
            m.appendTail(sb);

            parsedCalculation = sb.toString();
            logger.info("Parsed calculation: " + parsedCalculation);

        } catch (PatternSyntaxException pe) {
            logger.error("Regex syntax error ('" + pe.getPattern() + "') " + pe.getMessage());
        }
    }
    return parsedCalculation;
}

From source file:io.hops.hopsworks.api.admin.llap.LlapMonitorProxyServlet.java

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

    // Check if the user is logged in
    if (servletRequest.getUserPrincipal() == null) {
        servletResponse.sendError(403, "User is not logged in");
        return;//www.  ja  v  a 2  s  .  com
    }

    // Check that the user is an admin
    boolean isAdmin = servletRequest.isUserInRole("HOPS_ADMIN");
    if (!isAdmin) {
        servletResponse.sendError(Response.Status.BAD_REQUEST.getStatusCode(),
                "You don't have the access right for this application");
        return;
    }

    // The path we will receive is [host]/llapmonitor/llaphost/
    // We need to extract the llaphost to redirect the request
    String[] pathInfoSplits = servletRequest.getPathInfo().split("/");
    String llapHost = pathInfoSplits[1];

    //Now rewrite the URL
    StringBuffer urlBuf = new StringBuffer();//note: StringBuilder isn't supported by Matcher
    Matcher matcher = TEMPLATE_PATTERN.matcher(targetUriTemplate);
    if (matcher.find()) {
        matcher.appendReplacement(urlBuf, llapHost);
    }

    matcher.appendTail(urlBuf);
    String newTargetUri = urlBuf.toString();
    servletRequest.setAttribute(ATTR_TARGET_URI, newTargetUri);
    URI targetUriObj;
    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));

    super.service(servletRequest, servletResponse);
}

From source file:ch.ifocusit.livingdoc.plugin.publish.HtmlPostProcessor.java

private String replaceAll(String content, Pattern pattern, Function<MatchResult, String> replacer) {
    StringBuffer replacedContent = new StringBuffer();
    Matcher matcher = pattern.matcher(content);

    while (matcher.find()) {
        matcher.appendReplacement(replacedContent, replacer.apply(matcher.toMatchResult()));
    }//from   ww  w. j a va 2  s  .  c om

    matcher.appendTail(replacedContent);

    return replacedContent.toString();
}

From source file:com.hexidec.ekit.component.HTMLUtilities.java

private static String convertPointsToCm(String html) {
    StringBuffer sb = new StringBuffer();
    Pattern pTag = Pattern.compile("(<.+?style=\")(.+?)(\".*?>)", Pattern.DOTALL);
    Pattern pNumber = Pattern.compile("\\d+(?:\\.\\d*)");
    Matcher mTag = pTag.matcher(html);
    while (mTag.find()) {
        StringBuilder sbStyle = new StringBuilder(mTag.group(1));
        Map<String, String> mapStyle = DocumentUtil.styleToMap(mTag.group(2));
        for (Map.Entry<String, String> e : mapStyle.entrySet()) {
            String key = e.getKey();
            String value = e.getValue();
            if (pNumber.matcher(value).matches()) {
                value = LengthUnit.convertTo(Float.parseFloat(value), "cm");
            }// w  ww.jav a2  s.c  o m
            sbStyle.append(key + ": " + value + "; ");
        }
        sbStyle.append(mTag.group(3));
        mTag.appendReplacement(sb, Matcher.quoteReplacement(sbStyle.toString()));
    }
    mTag.appendTail(sb);
    return sb.toString();
}

From source file:org.dthume.couchdb.maven.ExpandIncludesMojo.java

private String expandIncludeReferences(final String js) throws IOException {
    if (null == js)
        return js;

    final StringBuffer sb = new StringBuffer();

    final Matcher matcher = INCLUDES_PATTERN.matcher(js);
    while (matcher.find()) {
        final String replacement = expandIncludeReferences(readInclude(matcher.group(1)));
        matcher.appendReplacement(sb, replacement);
        sb.append("\n");
    }/* ww w .ja  v  a2 s.co  m*/
    matcher.appendTail(sb);

    return sb.toString();
}

From source file:com.buaa.cfs.utils.StringUtils.java

/**
 * Matches a template string against a pattern, replaces matched tokens with the supplied replacements, and returns
 * the result.  The regular expression must use a capturing group.  The value of the first capturing group is used
 * to look up the replacement.  If no replacement is found for the token, then it is replaced with the empty
 * string./* w ww .j a v a 2  s.com*/
 * <p>
 * For example, assume template is "%foo%_%bar%_%baz%", pattern is "%(.*?)%", and replacements contains 2 entries,
 * mapping "foo" to "zoo" and "baz" to "zaz".  The result returned would be "zoo__zaz".
 *
 * @param template     String template to receive replacements
 * @param pattern      Pattern to match for identifying tokens, must use a capturing group
 * @param replacements Map<String, String> mapping tokens identified by the capturing group to their replacement
 *                     values
 *
 * @return String template with replacements
 */
public static String replaceTokens(String template, Pattern pattern, Map<String, String> replacements) {
    StringBuffer sb = new StringBuffer();
    Matcher matcher = pattern.matcher(template);
    while (matcher.find()) {
        String replacement = replacements.get(matcher.group(1));
        if (replacement == null) {
            replacement = "";
        }
        matcher.appendReplacement(sb, Matcher.quoteReplacement(replacement));
    }
    matcher.appendTail(sb);
    return sb.toString();
}

From source file:nl.ivonet.epub.strategy.epub.DitigalWatermarkRemovalStrategy.java

/**
 * removes watermark from a simple page.
 *//*from  w  ww  .j  a va2 s.  c om*/
private String removeWatermark1(final String html) {
    final Matcher matcher = WATERMARK_PAT.matcher(html);
    final StringBuffer sb = new StringBuffer();
    while (matcher.find()) {
        LOG.debug("Watermark = " + matcher.group());
        matcher.appendReplacement(sb, ">" + WAS_WATERMARK + "</p>");
    }
    matcher.appendTail(sb);
    return sb.toString();
}

From source file:info.magnolia.link.LinkUtil.java

/**
 * Converts provided html with links in UUID pattern format to any other kind of links based on provided link transformer.
 * @param str Html with UUID links/*  w  w w.  j  a v a2s  .  c o m*/
 * @param transformer Link transformer
 * @return converted html with links as created by provided transformer.
 * @see LinkTransformerManager
 */
public static String convertLinksFromUUIDPattern(String str, LinkTransformer transformer) throws LinkException {
    Matcher matcher = UUID_PATTERN.matcher(str);
    StringBuffer res = new StringBuffer();
    while (matcher.find()) {
        Link link = createLinkInstance(matcher.group(1), matcher.group(2), matcher.group(5), matcher.group(7),
                matcher.group(8), matcher.group(10), matcher.group(12));
        String replacement = transformer.transform(link);
        // Replace "\" with "\\" and "$" with "\$" since Matcher.appendReplacement treats these characters specially
        replacement = StringUtils.replace(replacement, "\\", "\\\\");
        replacement = StringUtils.replace(replacement, "$", "\\$");
        matcher.appendReplacement(res, replacement);
    }
    matcher.appendTail(res);
    return res.toString();
}