Example usage for java.util.regex Matcher replaceAll

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

Introduction

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

Prototype

public String replaceAll(Function<MatchResult, String> replacer) 

Source Link

Document

Replaces every 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.trustedanalytics.servicebroker.gearpump.service.externals.helpers.ConfigParser.java

public String ensureProperConfigFolder(String input, String provisionedFolder, String hdfsDirectory) {
    Matcher m = MASTERS_PATTERN.matcher(input);
    String replacement = String.format(REPLACEMENT_TEMPLATE, provisionedFolder, hdfsDirectory);
    return m.replaceAll(replacement);
}

From source file:net.sf.j2ep.servers.ClusterRequestWrapper.java

/**
 * Constructor, will check all cookies if they include
 * JSESSIONID. If they do any extra information about
 * which server this session was created for is removed.
 * //from w w w.j av  a  2s .c om
 * @param request The request we wrap.
 */
@SuppressWarnings("unchecked")
public ClusterRequestWrapper(HttpServletRequest request) {
    super(request);
    cookies = new Vector();

    Enumeration reqCookies = request.getHeaders("Cookie");
    while (reqCookies.hasMoreElements()) {
        String value = (String) reqCookies.nextElement();
        Matcher matcher = sessionPattern.matcher(value);
        String replaced = matcher.replaceAll("$1");
        if (log.isDebugEnabled() && !replaced.equals(value)) {
            log.debug("Session processed, serverId removed \"" + value + "\" >> " + replaced);
        }
        cookies.add(replaced);
    }
}

From source file:org.lanes.text.mining.UnithoodAnalyser.java

public boolean isUnit(String potentialphrase, String connector) {

    String left = "";
    String right = "";
    String current = "left";
    for (String token : potentialphrase.split(" ")) {

        if (!token.equals(connector) && current.equals("left")) {
            left = left + token + " ";
        } else if (token.equals(connector)) {
            current = "right";
        } else if (current.equals("right")) {
            right = right + token + " ";
        }/*from w w w. ja  va  2s  . c  om*/
    }
    Matcher replace1 = Pattern.compile(" $").matcher(left);
    left = replace1.replaceAll("");
    Matcher replace2 = Pattern.compile(" $").matcher(right);
    right = replace2.replaceAll("");

    boolean isunitornot = false;
    if (!left.equals("") && !right.equals("")) {
        isunitornot = isUnit(left, connector, right);
    }

    return isunitornot;
}

From source file:org.apache.hadoop.hbase.regionserver.metrics.SchemaMetrics.java

public static void validateMetricChanges(Map<String, Long> oldMetrics) {
    final Map<String, Long> newMetrics = getMetricsSnapshot();
    final Map<String, Long> allCfDeltas = new TreeMap<String, Long>();
    final Map<String, Long> allBlockCategoryDeltas = new TreeMap<String, Long>();
    final Map<String, Long> deltas = diffMetrics(oldMetrics, newMetrics);
    final Pattern cfTableMetricRE = useTableNameGlobally ? TABLE_AND_CF_NAME_RE : CF_NAME_RE;
    final Set<String> allKeys = new TreeSet<String>(oldMetrics.keySet());
    allKeys.addAll(newMetrics.keySet());

    for (SchemaMetrics cfm : tableAndFamilyToMetrics.values()) {
        for (String metricName : cfm.getAllMetricNames()) {
            if (metricName.startsWith(CF_PREFIX + CF_PREFIX)) {
                throw new AssertionError("Column family prefix used twice: " + metricName);
            }// w ww.j a v  a 2  s. co  m

            final long oldValue = getLong(oldMetrics, metricName);
            final long newValue = getLong(newMetrics, metricName);
            final long delta = newValue - oldValue;

            // Re-calculate values of metrics with no column family (or CF/table)
            // specified based on all metrics with CF (or CF/table) specified.
            if (delta != 0) {
                if (cfm != ALL_SCHEMA_METRICS) {
                    final String aggregateMetricName = cfTableMetricRE.matcher(metricName).replaceAll("");
                    if (!aggregateMetricName.equals(metricName)) {
                        LOG.debug("Counting " + delta + " units of " + metricName + " towards "
                                + aggregateMetricName);

                        putLong(allCfDeltas, aggregateMetricName,
                                getLong(allCfDeltas, aggregateMetricName) + delta);
                    }
                } else {
                    LOG.debug("Metric=" + metricName + ", delta=" + delta);
                }
            }

            Matcher matcher = BLOCK_CATEGORY_RE.matcher(metricName);
            if (matcher.find()) {
                // Only process per-block-category metrics
                String metricNoBlockCategory = matcher.replaceAll("");

                putLong(allBlockCategoryDeltas, metricNoBlockCategory,
                        getLong(allBlockCategoryDeltas, metricNoBlockCategory) + delta);
            }
        }
    }

    StringBuilder errors = new StringBuilder();
    for (String key : ALL_SCHEMA_METRICS.getAllMetricNames()) {
        long actual = getLong(deltas, key);
        long expected = getLong(allCfDeltas, key);
        if (actual != expected) {
            if (errors.length() > 0)
                errors.append("\n");
            errors.append("The all-CF metric " + key + " changed by " + actual
                    + " but the aggregation of per-CF/table metrics " + "yields " + expected);
        }
    }

    // Verify metrics computed for all block types based on the aggregation
    // of per-block-type metrics.
    for (String key : allKeys) {
        if (BLOCK_CATEGORY_RE.matcher(key).find() || key.contains(ALL_SCHEMA_METRICS.getBloomMetricName(false))
                || key.contains(ALL_SCHEMA_METRICS.getBloomMetricName(true))) {
            // Skip per-block-category metrics. Also skip bloom filters, because
            // they are not aggregated per block type.
            continue;
        }
        long actual = getLong(deltas, key);
        long expected = getLong(allBlockCategoryDeltas, key);
        if (actual != expected) {
            if (errors.length() > 0)
                errors.append("\n");
            errors.append("The all-block-category metric " + key + " changed by " + actual
                    + " but the aggregation of " + "per-block-category metrics yields " + expected);
        }
    }

    if (errors.length() > 0) {
        throw new AssertionError(errors.toString());
    }
}

From source file:no.sesat.search.view.velocity.BoldWordDirective.java

public boolean render(final InternalContextAdapter context, final Writer writer, final Node node)
        throws IOException, ResourceNotFoundException, ParseErrorException, MethodInvocationException {

    final int argCount = node.jjtGetNumChildren();

    if (argCount != 1) {

        String text = getArgument(context, node, 0);
        final String uquery = getArgument(context, node, 1);
        String query = org.apache.commons.lang.StringEscapeUtils.unescapeHtml(uquery);

        if (text == null) {
            writer.write("");
            return true;
        }//from   ww  w .  j a  v a2s .  c o m
        query = query.replaceAll("\"", "").replaceAll("'", "");

        final List list = Arrays.asList(query.split("[\\p{Punct}\\p{Space}]+"));

        for (int i = 0; i < list.size(); i++) {
            if (!list.get(i).toString().toLowerCase().equals("og")
                    && !list.get(i).toString().toLowerCase().equals("i")) {

                final String regexPattern = "(\\s|^)(" + list.get(i).toString() + ")(?![a-z])";
                final Pattern p = Pattern.compile(regexPattern, Pattern.CASE_INSENSITIVE);
                final Matcher m = p.matcher(text);
                text = m.replaceAll(" <b>$2</b>");
            }
        }
        writer.write(text);

        if (node.getLastToken().image.endsWith("\n")) {
            writer.write('\n');
        }

    } else {

        final String msg = '#' + getName() + " - wrong number of arguments";
        LOG.error(msg);
        return false;
    }

    return true;

}

From source file:org.kuali.coeus.common.impl.attachment.KcAttachmentServiceImpl.java

@Override
public String checkAndReplaceSpecialCharacters(String text) {
    String cleanText = text;/*  w  w w.j a v  a  2  s  .c om*/
    if (ObjectUtils.isNotNull(text)) {
        Pattern pattern = Pattern.compile(REGEX_TITLE_SPECIAL_CHARACTER_PATTERN);
        Matcher matcher = pattern.matcher(text);
        cleanText = matcher.replaceAll(REPLACEMENT_CHARACTER);
    }
    return cleanText;
}

From source file:fll.web.FullTournamentTest.java

/**
 * Create a string that's a valid file name.
 *//*from  w  w  w .j  a va 2s.com*/
private static String sanitizeFilename(final String str) {
    if (null == str || "".equals(str)) {
        return "NULL";
    } else {
        String ret = str;
        final Matcher illegalCharMatcher = ILLEGAL_CHAR_PATTERN.matcher(ret);
        ret = illegalCharMatcher.replaceAll("_");

        return ret;
    }
}

From source file:com.evolveum.midpoint.model.impl.filter.PatternFilter.java

@Override
public <T extends Object> PrismPropertyValue<T> apply(PrismPropertyValue<T> propertyValue) {
    Validate.notNull(propertyValue, "Node must not be null.");
    String value = getStringValue(propertyValue);
    if (StringUtils.isEmpty(value)) {
        return propertyValue;
    }//  w w  w.j ava  2 s .c  o  m

    Validate.notEmpty(getParameters(), "Parameters must not be null or empty.");
    List<Replace> replaces = getReplaces();
    for (Replace replace : replaces) {
        Matcher matcher = replace.getPattern().matcher(value);
        value = matcher.replaceAll(replace.getReplacement());
    }
    propertyValue.setValue((T) value);

    return propertyValue;
}

From source file:org.carrot2.source.boss.BossDocumentSource.java

@Override
protected void afterFetch(SearchEngineResponse response) {
    final String[] fields = new String[] { Document.TITLE, Document.SUMMARY };
    clean(response, keepHighlights, fields);

    // Remove all occurrences of <wbr>. It is used for optional breaking of words,
    // so removing (instead of replacing with space) is just right.
    // http://www.quirksmode.org/oddsandends/wbr.html
    for (Document document : response.results) {
        for (String field : fields) {
            final String originalField = document.getField(field);
            if (StringUtils.isNotBlank(originalField)) {
                final Matcher matcher = WBR_PATTERN.matcher(originalField);
                document.setField(field, matcher.replaceAll(""));
            }/*ww w  . java2  s . co m*/
        }
    }
}

From source file:org.lockss.extractor.SimpleHtmlMetaTagMetadataExtractor.java

protected void putValue(ArticleMetadata ret, String name, String content) {
    // filter raw HTML tags embedded within content -- publishers get sloppy
    content = HtmlUtil.stripHtmlTags(content);
    // remove character entities from content
    content = StringEscapeUtils.unescapeHtml4(content);
    // normalize multiple whitespace characters to a single space character
    Matcher m = whiteSpacePat.matcher(content);
    content = m.replaceAll(" ");

    if (log.isDebug3())
        log.debug3("Add: " + name + " = " + content);
    ret.putRaw(name, content);/*from   w ww. j a va2s.  c o m*/
}