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.adito.boot.ReplacementEngine.java

private void replaceInto(Pattern pattern, String replacementPattern, Replacer replacer, StringBuffer input,
        StringBuffer work) {//from  ww  w .j a  va  2 s  . co m
    work.ensureCapacity(input.length());
    work.setLength(0);
    if (log.isDebugEnabled())
        log.debug("Getting matcher for " + pattern.pattern());
    Matcher m = pattern.matcher(input);
    log.debug("Got matcher, finding first occurence.");
    while (m.find()) {
        if (log.isDebugEnabled())
            log.debug("Found occurence '" + m.group() + "'");
        String repl = replacer.getReplacement(pattern, m, replacementPattern);
        if (repl != null) {
            if (log.isDebugEnabled())
                log.debug("Found replacement, appending '" + repl + "'");
            if (encoder == null) {
                m.appendReplacement(work, Util.escapeForRegexpReplacement(repl));
            } else {
                m.appendReplacement(work, encoder.encode(Util.escapeForRegexpReplacement(repl)));
            }
        }
    }
    if (log.isDebugEnabled())
        log.debug("Processed matches, appending replacement.");
    m.appendTail(work);
}

From source file:com.comphenix.xp.messages.MessageFormatter.java

/**
 * Replaces parameters in the text with their respective value.
 * @param message - message to format.//from ww  w. j av a  2s.c om
 * @return Message with every parameter replaced with the corresponding value.
 */
public String formatMessage(String message) {

    if (message == null)
        return null;

    Map<String, ResourceHolder> lookup = getResultMapping();

    StringBuffer output = new StringBuffer();
    Matcher matcher = parameterPattern.matcher(message);

    // Simple variables
    // TODO: Add more variables.
    String sourceText = source != null ? source.getDisplayName() : "Unknown";
    String countText = count != null ? count.toString() : "N/A";

    while (matcher.find()) {

        String enumed = Utility.getEnumName(matcher.group());

        // Replace parameters
        if (enumed.equals("PLAYER"))
            matcher.appendReplacement(output, sourceText);
        else if (enumed.equals("COUNT"))
            matcher.appendReplacement(output, countText);
        else if (lookup.containsKey(enumed))
            matcher.appendReplacement(output, lookup.get(enumed).toString());
        else
            matcher.appendReplacement(output, "{CANNOT FIND " + matcher.group() + "}");
    }

    // Remember color
    matcher.appendTail(output);
    return formatUnescape(formatColor(output));
}

From source file:com.g3net.tool.StringUtils.java

/**
 * src?regex????????(handler)/*from   ww  w. j  a  v  a 2  s . c  o  m*/
 * ?????(regex?)?
 * 
 * @param src
 * @param regex
 *            ???? saa(\\d+)bb
 * @param handleGroupIndex
 *            regex?
 * @param hander
 * @return
 */
public static String replaceAll(String src, String regex, int handleGroupIndex, GroupHandler hander) {

    if (src == null || src.trim().length() == 0) {
        return "";
    }
    Matcher m = Pattern.compile(regex).matcher(src);

    StringBuffer sbuf = new StringBuffer();

    // perform the replacements:
    while (m.find()) {
        String value = m.group(handleGroupIndex);
        // int l = Integer.valueOf(value, 16).intValue();
        // char c=(char)(0x0ffff&l);
        // log.info(m.group(0));
        String handledStr = hander.handler(value);
        m.appendReplacement(sbuf, handledStr);

    }
    // Put in the remainder of the text:
    m.appendTail(sbuf);
    return sbuf.toString();
    // return null;
}

From source file:org.segrada.rendering.markup.DefaultMarkupFilter.java

/**
 * replace text parts with bibliographic annotations
 *
 * there are two://from   ww w .  ja  va2 s  .  c  o m
 *
 * [[haebler:rott]] => bibliographic reference -> replace with link to bib, but this will be done in the view
 *   so we do not have to replace this at all here...
 * [13:] => means page 13 in cited text => just decorated
 *
 * @param text input text
 * @return output text
 */
protected String annotateBibliographies(String text) {
    // check identity, if injector has been set
    Identity identity = injector != null ? injector.getInstance(Identity.class) : null;

    if (sourceService != null && identity != null) { // skipped in tests and if source not allowed
        // bibliographic references
        Matcher matcher = bibRefPattern.matcher(text);
        StringBuffer sb = new StringBuffer(text.length());
        while (matcher.find()) {
            String match = matcher.group(1);

            // try to get cached entry
            String replacement = sourceReferenceCache.get(match);
            if (replacement == null) {
                // find corresponding source
                ISource source = sourceService.findByRef(match);
                if (source == null)
                    replacement = "[[" + match + "]]"; // fallback
                else {
                    replacement = "<a href=\"source/show/" + source.getUid() + "\" class=\"sg-data-add\">"
                            + source.getShortTitle() + "</a>";
                }

                // write to cache
                sourceReferenceCache.put(match, replacement);
            }

            matcher.appendReplacement(sb, Matcher.quoteReplacement(replacement));
        }
        matcher.appendTail(sb);
        text = sb.toString();
    }

    // page reference
    text = text.replaceAll("\\[([0-9f]+:)\\]", "<span class=\"sg-label sg-info\">$1</span>");

    return text;
}

From source file:org.ops4j.pax.scanner.file.internal.FileScanner.java

/**
 * Reads the bundles from the file specified by the urlSpec.
 * {@inheritDoc}/*  ww  w. j  a va2  s . co m*/
 */
public List<ScannedBundle> scan(final ProvisionSpec provisionSpec)
        throws MalformedSpecificationException, ScannerException {
    NullArgumentException.validateNotNull(provisionSpec, "Provision spec");

    LOGGER.debug("Scanning [" + provisionSpec.getPath() + "]");
    List<ScannedBundle> scannedBundles = new ArrayList<ScannedBundle>();
    ScannerConfiguration config = createConfiguration();
    BufferedReader bufferedReader = null;
    try {
        try {
            bufferedReader = new BufferedReader(new InputStreamReader(
                    URLUtils.prepareInputStream(provisionSpec.getPathAsUrl(), !config.getCertificateCheck())));
            Integer defaultStartLevel = getDefaultStartLevel(provisionSpec, config);
            Boolean defaultStart = getDefaultStart(provisionSpec, config);
            Boolean defaultUpdate = getDefaultUpdate(provisionSpec, config);
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                String trimmedLine = line.trim();
                if (trimmedLine.length() > 0 && !trimmedLine.startsWith(COMMENT_SIGN)) {
                    if (trimmedLine.startsWith(PROPERTY_PREFIX)) {
                        Matcher matcher = PROPERTY_PATTERN.matcher(trimmedLine);
                        if (!matcher.matches() || matcher.groupCount() != 2) {
                            throw new ScannerException("Invalid property: " + line);
                        }
                        String key = matcher.group(1);
                        String value = matcher.group(2);
                        StringBuffer stringBuffer = new StringBuffer(value.length());
                        for (matcher = QUOTED_PROPERTY_VALUE_PATTERN.matcher(value); matcher.find(); matcher
                                .appendReplacement(stringBuffer, value)) {
                            String group = matcher.group();
                            value = group.substring(1, group.length() - 1).replace("\\\"", "\"").replace("$",
                                    "\\$");
                        }
                        int index = stringBuffer.length();
                        matcher.appendTail(stringBuffer);
                        if (index < stringBuffer.length() && !(stringBuffer.indexOf(" ", index) < 0
                                && stringBuffer.indexOf("\"", index) < 0)) {
                            throw new ScannerException("Invalid property: " + line);
                        }
                        value = SystemPropertyUtils.resolvePlaceholders(stringBuffer.toString());
                        System.setProperty(key, value);
                    } else {
                        line = SystemPropertyUtils.resolvePlaceholders(line);
                        final ScannedFileBundle scannedFileBundle = new ScannedFileBundle(line,
                                defaultStartLevel, defaultStart, defaultUpdate);
                        scannedBundles.add(scannedFileBundle);
                        LOGGER.debug("Installing bundle [" + scannedFileBundle + "]");
                    }
                }
            }
        } finally {
            if (bufferedReader != null) {
                bufferedReader.close();
            }
        }
    } catch (IOException e) {
        throw new ScannerException("Could not parse the provision file", e);
    }
    return scannedBundles;
}

From source file:org.codice.ddf.spatial.ogc.csw.catalog.common.source.CswFilterFactory.java

/**
 * The WKT passed into the spatial methods has the coordinates ordered in LON/LAT. This method
 * will convert the WKT to LAT/LON ordering.
 *//*from w  ww  . j a  va 2s  .  c om*/
private String convertWktToLatLonOrdering(String wktInLonLat) {

    if (cswAxisOrder != CswAxisOrder.LON_LAT) {
        LOGGER.debug("Converting WKT from LON/LAT coordinate ordering to LAT/LON coordinate ordering.");

        // Normalize all whitespace in WKT before processing.
        wktInLonLat = normalizeWhitespaceInWkt(wktInLonLat);

        Matcher matcher = COORD_PATTERN.matcher(wktInLonLat);

        StringBuffer stringBuffer = new StringBuffer();

        while (matcher.find()) {
            String lonLatCoord = matcher.group();
            String latLonCoord = StringUtils.reverseDelimited(lonLatCoord, ' ');
            LOGGER.debug("Converted LON/LAT coord: ({}) to LAT/LON coord: ({}).", lonLatCoord, latLonCoord);
            matcher.appendReplacement(stringBuffer, latLonCoord);
        }

        matcher.appendTail(stringBuffer);

        String wktInLatLon = stringBuffer.toString();
        LOGGER.debug("Original WKT with coords in LON/LAT ordering:  {}", wktInLonLat);
        LOGGER.debug("Converted WKT with coords in LAT/LON ordering: {}", wktInLatLon);

        return wktInLatLon;
    } else {
        LOGGER.debug("The configured CSW source requires coordinates in LON/LAT ordering.");
        return wktInLonLat;
    }
}

From source file:org.codice.ddf.spatial.ogc.csw.catalog.source.CswFilterFactory.java

/**
 * The WKT passed into the spatial methods has the coordinates ordered in LON/LAT. This method
 * will convert the WKT to LAT/LON ordering.
 *//*  w w w .j  av  a2 s. c  o  m*/
private String convertWktToLatLonOrdering(String wktInLonLat) {

    if (!isLonLatOrder) {
        LOGGER.debug("Converting WKT from LON/LAT coordinate ordering to LAT/LON coordinate ordering.");

        // Normalize all whitespace in WKT before processing.
        wktInLonLat = normalizeWhitespaceInWkt(wktInLonLat);

        Matcher matcher = COORD_PATTERN.matcher(wktInLonLat);

        StringBuffer stringBuffer = new StringBuffer();

        while (matcher.find()) {
            String lonLatCoord = matcher.group();
            String latLonCoord = StringUtils.reverseDelimited(lonLatCoord, ' ');
            LOGGER.debug("Converted LON/LAT coord: ({}) to LAT/LON coord: ({}).", lonLatCoord, latLonCoord);
            matcher.appendReplacement(stringBuffer, latLonCoord);
        }

        matcher.appendTail(stringBuffer);

        String wktInLatLon = stringBuffer.toString();
        LOGGER.debug("Original WKT with coords in LON/LAT ordering:  {}", wktInLonLat);
        LOGGER.debug("Converted WKT with coords in LAT/LON ordering: {}", wktInLatLon);

        return wktInLatLon;
    } else {
        LOGGER.debug("The configured CSW source requires coordinates in LON/LAT ordering.");
        return wktInLonLat;
    }
}

From source file:com.android.tools.idea.editors.theme.ThemeEditorUtilsTest.java

private void compareWithGoldenFile(@NotNull String text, @NotNull String goldenFile) throws IOException {
    final File file = new File(goldenFile);
    String goldenText = FileUtils.readFileToString(file);
    goldenText = goldenText.replace("$$ANDROID_SDK_PATH", sdkPlatformPath);
    Matcher matcher = OPERATION_PATTERN.matcher(goldenText);
    StringBuffer processedGoldenText = new StringBuffer();

    while (matcher.find()) {
        String operation = matcher.group(1);
        String value = matcher.group(2);
        if (operation.equals("MAKE_URL")) {
            value = SdkUtils.fileToUrl(new File(value)).toString();
        } else if (operation.equals("MAKE_SYSTEM_DEPENDENT_PATH")) {
            value = PathUtil.toSystemDependentName(value);
            // escape all the backslashes so they don't get treated as backreferences by the regex engine later
            if (File.separatorChar == '\\') {
                value = value.replace("\\", "\\\\");
            }/*from   ww  w . ja v a 2s. co  m*/
        } else {
            // Ignore if we don't know how to handle that - may be accidental pattern match
            continue;
        }
        matcher.appendReplacement(processedGoldenText, value);
    }
    matcher.appendTail(processedGoldenText);

    // Add line breaks after "<BR/>" tags for results that are easier to read.
    // Golden files are already have these line breaks, so there's no need to process them the same way.
    text = StringUtil.replace(text, "<BR/>", "<BR/>\n");

    assertEquals(String.format("Comparing to golden file %s failed", file.getCanonicalPath()),
            processedGoldenText.toString(), text);
}

From source file:org.nuclos.client.wizard.NuclosEntityWizardStaticModel.java

public List<String> getFieldsInNodeLabel() {
    List<String> lstFields = new ArrayList<String>();

    String sField = getNodeLabel();
    Pattern referencedEntityPattern = Pattern.compile("[$][{][\\w\\[\\]]+[}]");
    Matcher referencedEntityMatcher = referencedEntityPattern.matcher(sField);
    StringBuffer sb = new StringBuffer();

    while (referencedEntityMatcher.find()) {
        Object value = referencedEntityMatcher.group().substring(2,
                referencedEntityMatcher.group().length() - 1);

        String sName = value.toString();
        referencedEntityMatcher.appendReplacement(sb, sName);
    }//from   w  w  w  . j  a v  a  2s . c  o  m

    // complete the transfer to the StringBuffer
    referencedEntityMatcher.appendTail(sb);
    sField = sb.toString();

    String s = StringUtils.replace(StringUtils.replace(getNodeLabel(), "]", " "), "[", " ");
    if (s != null) {
        StringTokenizer st = new StringTokenizer(s, " ");
        while (st.hasMoreTokens()) {
            lstFields.add(st.nextToken());
        }
    }
    return lstFields;
}

From source file:com.ibm.jaggr.service.impl.modulebuilder.css.CSSModuleBuilder.java

/**
 * Minifies a CSS string by removing comments and excess white-space, as well as 
 * some unneeded tokens.//w  w  w  .  j  a  v a2 s. c om
 * 
 * @param css The contents of a CSS file as a String
 * @param uri The URI for the CSS file
 * @return
 */
protected String minify(String css, IResource res) {

    // replace all quoted strings and url(...) patterns with unique ids so that 
    // they won't be affected by whitespace removal.
    LinkedList<String> quotedStringReplacements = new LinkedList<String>();
    Matcher m = quotedStringPattern.matcher(css);
    StringBuffer sb = new StringBuffer();
    int i = 0;
    while (m.find()) {
        String text = (m.group(1) != null) ? ("url(" + StringUtils.trim(m.group(1)) + ")") : //$NON-NLS-1$ //$NON-NLS-2$
                m.group(0);
        quotedStringReplacements.add(i, text);
        String replacement = "%%" + QUOTED_STRING_MARKER + (i++) + "__%%"; //$NON-NLS-1$ //$NON-NLS-2$
        m.appendReplacement(sb, ""); //$NON-NLS-1$
        sb.append(replacement);
    }
    m.appendTail(sb);
    css = sb.toString();

    // Get rid of extra whitespace
    css = whitespacePattern.matcher(css).replaceAll(" "); //$NON-NLS-1$
    css = endsPattern.matcher(css).replaceAll(""); //$NON-NLS-1$
    css = closeBracePattern.matcher(css).replaceAll("}"); //$NON-NLS-1$
    m = delimitersPattern.matcher(css);
    sb = new StringBuffer();
    while (m.find()) {
        String text = m.group(1);
        m.appendReplacement(sb, ""); //$NON-NLS-1$
        sb.append(text.length() == 1 ? text : text.replace(" ", "")); //$NON-NLS-1$ //$NON-NLS-2$
    }
    m.appendTail(sb);
    css = sb.toString();

    // restore quoted strings and url(...) patterns
    m = QUOTED_STRING_MARKER_PAT.matcher(css);
    sb = new StringBuffer();
    while (m.find()) {
        i = Integer.parseInt(m.group(1));
        m.appendReplacement(sb, ""); //$NON-NLS-1$
        sb.append(quotedStringReplacements.get(i));
    }
    m.appendTail(sb);
    css = sb.toString();

    return css.toString();
}