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:com.hexidec.ekit.component.HTMLUtilities.java

private static String converteBlocosEmParagrafos(String str) {

    Matcher m = pBlocos.matcher(str);
    if (!m.find()) {
        return str;
    }/*from w w  w .ja v  a  2  s .  co  m*/

    StringBuffer sb = new StringBuffer();
    String antes, depois;
    do {
        antes = m.group(1);
        depois = m.group(2);

        m.appendReplacement(sb, Matcher.quoteReplacement(antes + "p" + depois));

    } while (m.find());

    m.appendTail(sb);

    return sb.toString();
}

From source file:de.uni.bremen.monty.moco.ast.expression.literal.StringLiteral.java

/** replaces escape sequences of string literals by the LLVM IR equivalents
 *
 * @param value/* w  w  w.j a va 2  s . c  om*/
 *            the string which should be escaped
 * @return an escaped string */
public static String replaceEscapeSequences(String value) {
    // replace escape sequences
    value = value.replace("\\t", "\\09"); // horizontal tab
    value = value.replace("\\b", "\\08"); // backspace
    value = value.replace("\\n", "\\0A"); // line feed
    value = value.replace("\\r", "\\0D"); // carriage return
    value = value.replace("\\f", "\\0C"); // formfeed
    value = value.replace("\\'", "\\27"); // single quote
    value = value.replace("\\\"", "\\22"); // double quote
    value = value.replace("\\\\", "\\5C"); // backslash

    // replace unicode escape sequences by utf-8 codes
    StringBuffer output = new StringBuffer();
    Pattern regex = Pattern.compile("(\\\\u....)|\\P{ASCII}");
    Matcher matcher = regex.matcher(value);
    byte[] utf8;
    while (matcher.find()) {
        String replacement = "";

        if (matcher.group().startsWith("\\u")) {
            // convert hexadecimal unicode number to utf-8 encoded bytes
            utf8 = Character.toString((char) Integer.parseInt(matcher.group().substring(2), 16))
                    .getBytes(StandardCharsets.UTF_8);
        } else {
            // convert a unicode character to utf-8 encoded bytes
            utf8 = matcher.group().getBytes(StandardCharsets.UTF_8);
        }
        // convert utf-8 bytes to hex strings (for LLVM IR)
        for (byte c : utf8) {
            replacement += String.format("\\\\%02x", c);
        }
        matcher.appendReplacement(output, replacement);
    }
    matcher.appendTail(output);

    return output.toString();
}

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

protected static String formatMessage(String messageTemplate, Map<String, String> variableValues) {

    StringBuffer result = new StringBuffer();

    // collect keys and values to determine value size limit if needed
    final Map<String, String> replaceMap = new HashMap<String, String>();

    final Matcher matcher = PROPERTY_NAME_PATTERN.matcher(messageTemplate);
    int count = 0;
    while (matcher.find()) {
        final String key = matcher.group(1);
        final String value = variableValues.get(key);

        if (value != null) {
            replaceMap.put(key, value);//from   w w  w .j av a2  s . co  m
            matcher.appendReplacement(result, Matcher.quoteReplacement(value));
        } else {
            matcher.appendReplacement(result, Matcher.quoteReplacement(matcher.group()));
        }

        count++;
    }
    matcher.appendTail(result);

    // check if the result exceeds MAX_LENGTH for formatted properties
    if (!replaceMap.isEmpty() && result.length() > MAX_LENGTH) {
        // sort values according to size
        final SortedSet<String> values = new TreeSet<String>(new Comparator<String>() {
            public int compare(String o1, String o2) {
                return o1.length() - o2.length();
            }
        });
        values.addAll(replaceMap.values());

        // find total value characters allowed
        int available = MAX_LENGTH - PROPERTY_NAME_PATTERN.matcher(messageTemplate).replaceAll("").length();

        // fit values from small to large in the allowed size to determine the maximum average
        int averageLength = available / count;
        for (String value : values) {
            final int length = value.length();
            if (length > averageLength) {
                break;
            }
            available -= length;
            count--;
            averageLength = available / count;
        }

        // replace values
        matcher.reset();
        result.delete(0, result.length());
        while (matcher.find()) {
            String value = replaceMap.get(matcher.group(1));
            if (value != null && value.length() > averageLength) {
                value = value.substring(0, averageLength);
            }
            matcher.appendReplacement(result, value != null ? value : matcher.group());
        }
        matcher.appendTail(result);
    }

    return result.toString();
}

From source file:Main.java

public static String unescapeXML(final String xml) {
    Pattern xmlEntityRegex = Pattern.compile("&(#?)([^;]+);");
    //Unfortunately, Matcher requires a StringBuffer instead of a StringBuilder
    StringBuffer unescapedOutput = new StringBuffer(xml.length());

    Matcher m = xmlEntityRegex.matcher(xml);
    Map<String, String> builtinEntities = null;
    String entity;/*  w  w  w. jav  a2 s .com*/
    String hashmark;
    String ent;
    int code;
    while (m.find()) {
        ent = m.group(2);
        hashmark = m.group(1);
        if ((hashmark != null) && (hashmark.length() > 0)) {
            code = Integer.parseInt(ent);
            entity = Character.toString((char) code);
        } else {
            //must be a non-numerical entity
            if (builtinEntities == null) {
                builtinEntities = buildBuiltinXMLEntityMap();
            }
            entity = builtinEntities.get(ent);
            if (entity == null) {
                //not a known entity - ignore it
                entity = "&" + ent + ';';
            }
        }
        m.appendReplacement(unescapedOutput, entity);
    }
    m.appendTail(unescapedOutput);

    return unescapedOutput.toString();
}

From source file:net.sf.sahi.util.Utils.java

@SuppressWarnings("unchecked")
public static String substitute(final String content, final Map substitutions) {

    StringBuffer patternBuf = new StringBuffer();
    int i = 0;//from   w w w  . j a  va2s . c o  m
    Iterator<?> keys = substitutions.keySet().iterator();
    while (keys.hasNext()) {
        String key = (String) keys.next();
        patternBuf.append(i++ == 0 ? "" : "|").append("\\$").append(key);
    }
    Pattern pattern = Pattern.compile(patternBuf.toString());
    patternBuf = null;
    Matcher matcher = pattern.matcher(content);

    StringBuffer buf = new StringBuffer();
    while (matcher.find()) {
        String key = matcher.group(0).substring(1);
        String replaceStr = ((String) substitutions.get(key)).replace("\\", "\\\\").replaceAll("\\$", "SDLR");
        matcher.appendReplacement(buf, replaceStr);
    }
    matcher.appendTail(buf);
    return buf.toString().replaceAll("SDLR", "\\$");
}

From source file:info.magnolia.cms.util.LinkUtil.java

/**
 * Convert the mangolia format to absolute (repository friendly) pathes
 * @param str html//w w  w  .j  a  va 2s . co  m
 * @return html with absolute links
 */
public static String convertUUIDsToAbsoluteLinks(String str) {
    Matcher matcher = uuidPattern.matcher(str);
    StringBuffer res = new StringBuffer();
    while (matcher.find()) {
        String absolutePath = null;
        String uuid = matcher.group(1);

        if (StringUtils.isNotEmpty(uuid)) {
            absolutePath = LinkUtil.makeAbsolutePathFromUUID(uuid);
        }

        // can't find the uuid
        if (StringUtils.isEmpty(absolutePath)) {
            absolutePath = matcher.group(2);
            log.error("Was not able to get the page by jcr:uuid nor by mgnl:uuid. Will use the saved path {}",
                    absolutePath);
        }
        matcher.appendReplacement(res, absolutePath + ".html"); //$NON-NLS-1$
    }
    matcher.appendTail(res);
    return res.toString();
}

From source file:org.nuxeo.theme.html.CSSUtils.java

public static String rgbToHex(String value) {
    value = value.replaceAll("\\s", "");
    final Matcher m = rgbDigitPattern.matcher(value);
    final StringBuffer sb = new StringBuffer();
    while (m.find()) {
        final String[] rgb = m.group(1).split(",");
        final StringBuffer hexcolor = new StringBuffer();
        for (String element : rgb) {
            final int val = Integer.parseInt(element);
            if (val < 16) {
                hexcolor.append("0");
            }/*  www  .j ava  2  s  .co m*/
            hexcolor.append(Integer.toHexString(val));
        }
        m.appendReplacement(sb, hexcolor.toString());
    }
    m.appendTail(sb);
    return sb.toString();
}

From source file:com.icesoft.faces.webapp.parser.JspPageToDocument.java

static String toSingletonTag(String pattern, String input) {
    Pattern tagPattern = Pattern.compile(pattern, Pattern.DOTALL);
    Matcher tagMatcher = tagPattern.matcher(input);
    StringBuffer tagBuf = new StringBuffer();
    while (tagMatcher.find()) {
        String tagName = tagMatcher.group(1);
        String attributes = tagMatcher.group(2);
        tagMatcher.appendReplacement(tagBuf, escapeBackreference("<" + tagName + attributes + "/>"));
    }/*  www .  j av a  2 s .  c om*/
    tagMatcher.appendTail(tagBuf);
    return tagBuf.toString();
}

From source file:org.openflexo.toolbox.FileUtils.java

/**
 * @param componentName/* w w  w  .  j a va 2  s .  c o m*/
 * @return
 */
public static String getValidFileName(String fileName) {
    StringBuffer sb = new StringBuffer();
    Matcher m = UNACCEPTABLE_SLASH_PATTERN.matcher(fileName);
    while (m.find()) {
        m.appendReplacement(sb, "/");
    }
    m.appendTail(sb);
    m = UNACCEPTABLE_CHARS_PATTERN.matcher(sb.toString());
    sb = new StringBuffer();
    while (m.find()) {
        m.appendReplacement(sb, "_");
    }
    m.appendTail(sb);
    return sb.toString();
}

From source file:org.blockfreie.element.hydrogen.murikate.ApplicationUtil.java

/**
 * Expands expression of the form. ${evn:NAME} expands to the evniroment
 * variable $NAME ${prop:NAME} expands to the property $NAME
 * /*from w ww  .  java2  s  .  c o  m*/
 * seen as a replacement of the java.text.MessageFormat
 * 
 * @param value
 *            to be expanded
 * @return the expanded string
 */
public static String elExpand(String value) {
    StringBuffer buffer = new StringBuffer();
    Matcher matcher = EL_PATTERN.matcher(value);
    while (matcher.find()) {
        String prelude = matcher.group(1);
        String name = matcher.group(2);
        String replacement;
        if (EL_ENV_KEY.equals(prelude)) {
            replacement = System.getenv().get(name);
        } else if (EL_PROP_KEY.equals(prelude)) {
            replacement = System.getProperty(name);
        } else {
            replacement = matcher.group();
            LOGGER.log(Level.WARNING, String.format("Unknown expansion : '%s' : ignoring", replacement));
        }
        replacement = replacement.replaceAll("\\$", "\\\\\\$"); // 1. fix $
        // bug with replacement - Illegal groupreference
        matcher.appendReplacement(buffer, replacement);
    }
    matcher.appendTail(buffer);
    return buffer.toString();
}