Example usage for java.util.regex Matcher replaceFirst

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

Introduction

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

Prototype

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

Source Link

Document

Replaces the first 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:GIST.IzbirkomExtractor.AbbrList.java

/**
 * Expand all abbreviations in the given streetname; only the first
 * expansion will be used//  ww  w . jav  a 2 s  .  c o m
 * 
 * @param streetName
 * @return street name with expanded abbreviations
 */
public String expandAbbreviations(String streetName) {

    Matcher mat = getAbbreviationsPattern().matcher(streetName);
    if (mat.find()) {
        // FIXME: must perform exactly like "create all expansions"
        String match = mat.group(1);
        Abbreviation ab = abbrevs.get(match);
        String exp = ab.getExpansions().get(0);
        streetName = mat.replaceFirst(exp);
    }

    return streetName;
}

From source file:iristk.cfg.ABNFGrammar.java

private List<Object> parseMatches(String matches) throws IOException, GrammarException {
    //System.out.println(matches);
    checkBalance(matches, '{', '}');
    checkBalance(matches, '(', ')');
    checkBalance(matches, '[', ']');
    checkBalance(matches, '<', '>');

    //System.out.println("#" + matches + "#");
    matches = matches.trim();// w  ww  . jav a 2 s . c  o  m
    List<String> groups = split(matches, "|");
    if (groups.size() > 1) {
        OneOf oneof = new OneOf();
        for (String gr : groups) {
            List<Object> grl = parseMatches(gr);
            if (grl.size() == 1) {
                oneof.add(grl.get(0));
            } else {
                oneof.add(new Item(grl));
            }
        }
        List<Object> result = new ArrayList<Object>();
        result.add(oneof);
        return result;
    }
    List<Object> result = new ArrayList<Object>();
    groups = split(matches, " ");
    if (groups.size() > 1) {
        for (String gr : groups) {
            List<Object> grl = parseMatches(gr);
            if (grl.size() == 1) {
                result.add(grl.get(0));
            } else {
                result.add(new Item(grl));
            }
        }
    } else {
        String group = groups.get(0);
        if (group.startsWith("(")) {
            List<Object> tag = null;
            if (group.endsWith("}")) {
                Matcher m = Pattern.compile("\\{[^\\(\\{\\}\\)]*\\}$").matcher(group);
                m.find();
                tag = parseMatches(m.group(0));
                group = m.replaceFirst("").trim();
            }
            List<Object> list = parseMatches(group.substring(1, group.length() - 1));
            if (list.size() == 1)
                result.add(list.get(0));
            else
                result.add(new Item(list));
            if (tag != null)
                result.addAll(tag);
        } else if (group.startsWith("$<")) {
            String ref = group.replace("$<", "").replace(">", "").trim();
            try {
                ABNFGrammar include = new ABNFGrammar(uri == null ? new URI(ref) : uri.resolve(ref));
                include(include);
                result.add(new RuleRef(include.includeRoot()));
            } catch (URISyntaxException e) {
                e.printStackTrace();
            }
        } else if (group.startsWith("$")) {
            result.add(new RuleRef(group.substring(1)));
        } else if (group.startsWith("{")) {
            if (!group.endsWith("}"))
                throw new GrammarException("Bad expression: " + group);
            result.add(new Tag(group.substring(1, group.length() - 1)));
        } else if (group.startsWith("[")) {
            if (!group.endsWith("]"))
                throw new GrammarException("Bad expression: " + group);
            List<Object> list = parseMatches(group.substring(1, group.length() - 1));
            Item optional = new Item(list);
            optional.setRepeat(0, 1);
            result.add(optional);
        } else {
            result.add(group);
        }
    }
    return result;
}

From source file:com.ocpsoft.pretty.PrettyContext.java

/**
 * Must create instance through the initialize() method
 *//*w w  w  .  j a  v a  2 s .  c o m*/
protected PrettyContext(final HttpServletRequest request) {
    Assert.notNull(request, "HttpServletRequest argument was null");

    // attribute is set by PrettyFacesRewriteLifecycleListener before
    config = (PrettyConfig) request.getAttribute(CONFIG_KEY);

    // not sure if this can happen any more, but we'll keep it for now
    if (config == null) {
        config = new PrettyConfig();
    }

    contextPath = request.getContextPath();
    String requestUrl = stripContextPath(request.getRequestURI());
    Matcher sessionIdMatcher = JSESSIONID_PATTERN.matcher(requestUrl);
    if (sessionIdMatcher.matches()) {
        requestUrl = sessionIdMatcher.replaceFirst(JSESSIONID_REPLACEMENT);
    }

    String encoding = request.getCharacterEncoding() == null ? DEFAULT_ENCODING
            : request.getCharacterEncoding();

    requestURL = new URL(requestUrl);
    requestURL.setEncoding(encoding);
    requestURL = requestURL.decode();

    requestQuery = QueryString.build(request.getQueryString());

    log.trace("Initialized PrettyContext");
}

From source file:org.jboss.set.aphrodite.issue.trackers.jira.JiraIssueTracker.java

private String correctPath(String path) {
    Matcher m = PROJECTS_ISSUE_PATTERN.matcher(path);
    if (m.find()) {
        return m.replaceFirst(BROWSE_ISSUE_PATH);
    }/*from  w  w w. j  a  v  a 2  s. c  o  m*/
    return path;
}

From source file:nl.mpi.lamus.archive.implementation.LamusArchiveFileHelper.java

/**
 * @see ArchiveFileHelper#correctPathElement(java.lang.String, java.lang.String) 
 *///  ww w .ja v  a2 s  .  c  om
@Override
public String correctPathElement(String pathElement, String reason) {
    String temp = pathElement.replaceAll("\\&[^;]+;", "_"); // replace xml variables
    // 20..2c: space ! " # $ % &amp;  ' ( ) * +   3a..40: : ; &lt; = > ? @
    // 5b..60: [ \\ ] ^ _    7b..7f: { | } ~
    // temp=temp.replaceAll("[\\x00-\\x2C\\x2F\\x3A-\\x40\\x5B-\\x60\\x7B-\\xFF]", "_"); // replace special chars
    // temp=temp.replaceAll("[\\u0100-\\uffff]", "_"); // replace special chars
    // safe minimal MPI names may only contain [A-Za-z0-9._-], but URI can also contain
    // ! ~ * ' ( ) "unreserved" and : @ &amp; = + $ , "reserved minus ; / ?" at many
    // places. Reserved ; / ? : @ &amp; = + $ , have special meaning, see RFC2396.
    // Whitespace  is never allowed in URI, but %nn hex escapes can often be used.
    temp = temp.replaceAll("[^A-Za-z0-9._-]", "_"); // replace all except known good chars

    String result = temp;

    // in case the pathElement already contained "__" (without any invalid characters), it should stay unchanged
    if (!temp.equals(pathElement)) {
        Pattern pat = Pattern.compile("__"); // shorten double replacements
        Matcher mat = pat.matcher(temp);
        while (mat.find(0))
            mat.reset(mat.replaceFirst("_"));
        result = mat.replaceFirst("_");
    }

    if (result.length() > maxDirectoryNameLength) { // truncate but try to keep extension
        int dot = result.lastIndexOf('.');
        String suffix = "...";
        if (dot >= 0 && (result.length() - dot) <= 7) // at most '.123456'
            suffix += result.substring(dot); // otherwise: no extension to preserve!
        // archivable files all have (2) / 3 / 4 char extensions, '.class' has 5 chars
        result = result.substring(0, maxDirectoryNameLength - suffix.length()) + suffix; // suffix.length: 3..10
    }
    if (!result.equals(pathElement)) {
        if ("getFileTitle".equals(reason)) { // log noise reduction ;-)
            logger.info("correctPathElement: " + reason + ": " + pathElement + " -> " + result);
        } else {
            logger.warn("correctPathElement: " + reason + ": " + pathElement + " -> " + result);
        }
    }
    return result;

}

From source file:org.apache.solr.metrics.reporters.solr.SolrReporter.java

@Override
public void report() {
    String url = urlProvider.get();
    // if null then suppress reporting
    if (url == null) {
        return;/*w w w.  ja  va 2s.c  o  m*/
    }

    SolrClient solr;
    if (cloudClient) {
        solr = clientCache.getCloudSolrClient(url);
    } else {
        solr = clientCache.getHttpSolrClient(url);
    }
    UpdateRequest req = new UpdateRequest(handler);
    req.setParams(params);
    compiledReports.forEach(report -> {
        Set<String> registryNames = metricManager.registryNames(report.registryPattern);
        registryNames.forEach(registryName -> {
            String label = report.label;
            if (label != null && label.indexOf('$') != -1) {
                // label with back-references
                Matcher m = report.registryPattern.matcher(registryName);
                label = m.replaceFirst(label);
            }
            final String effectiveLabel = label;
            String group = report.group;
            if (group.indexOf('$') != -1) {
                // group with back-references
                Matcher m = report.registryPattern.matcher(registryName);
                group = m.replaceFirst(group);
            }
            final String effectiveGroup = group;
            MetricUtils.toSolrInputDocuments(metricManager.registry(registryName),
                    Collections.singletonList(report.filter), MetricFilter.ALL, MetricUtils.PropertyFilter.ALL,
                    skipHistograms, skipAggregateValues, compact, metadata, doc -> {
                        doc.setField(REGISTRY_ID, registryName);
                        doc.setField(GROUP_ID, effectiveGroup);
                        if (effectiveLabel != null) {
                            doc.setField(LABEL_ID, effectiveLabel);
                        }
                        req.add(doc);
                    });
        });
    });

    // if no docs added then don't send a report
    if (req.getDocuments() == null || req.getDocuments().isEmpty()) {
        return;
    }
    try {
        //log.info("%%% sending to " + url + ": " + req.getParams());
        solr.request(req);
    } catch (Exception e) {
        log.debug("Error sending metric report", e.toString());
    }

}

From source file:org.apache.hadoop.hdfs.server.datanode.TestDataNodeRollingUpgrade.java

private boolean isBlockFileInPrevious(File blockFile) {
    Pattern blockFilePattern = Pattern.compile(
            String.format("^(.*%1$scurrent%1$s.*%1$s)(current)(%1$s.*)$", Pattern.quote(File.separator)));
    Matcher matcher = blockFilePattern.matcher(blockFile.toString());
    String previousFileName = matcher.replaceFirst("$1" + "previous" + "$3");
    return ((new File(previousFileName)).exists());
}

From source file:org.diffkit.db.DKDBType.java

private String decodeSqlTypeName() {
    String enumName = this.toString();
    Matcher matcher = getFlavorManglePattern().matcher(enumName);
    if (!matcher.find())
        return enumName;
    return matcher.replaceFirst("");
}

From source file:de.innovationgate.wgpublisher.RTFEncodingFormatter.java

public String format(Object obj) throws FormattingException {

    try {/*from w w  w.  ja  v a2s . c o  m*/

        String text = (String) obj;
        _generateDataURL = (Boolean) _scriptletEngineParameters
                .get(RhinoExpressionEngine.SCRIPTLETOPTION_IMAGEURL_AS_DATAURL);
        if (_generateDataURL == null) {
            _generateDataURL = Boolean.FALSE;
        }

        // Step one: Resolve scriptlets
        RhinoExpressionEngine engine = ExpressionEngineFactory.getTMLScriptEngine();
        text = engine.resolveScriptlets(text, _context, _scriptletEngineParameters);

        // Step two: Filter out all old relative links and replace them with dynamic URLs
        // We can ONLY do this in pure display mode. If field gets rendered for RTF editor we must prevent this because
        // it would lead to the storage of those dynamic URLs
        if (!_editMode) {
            // replace qualified and unqualified attachment links
            text = WGUtils.strReplace(text, "=\"../", this, true);
            // replace content links
            text = replaceContentLinks(text);
        }

        if (_editMode && WGUtils.stringToBoolean(System.getProperty(SYSPROP_FORCE_HTML_CLEANUP, "false"))) {
            // remove RTF-Editor declarations if contained in item value (possible due to copy&paste operations in the CM)
            Pattern rtfEditorDeclarationPatter = Pattern.compile("(<span[^>]*class=\"WGA-Item[^\"]*[^>]*>)",
                    Pattern.DOTALL);
            Matcher matcher = rtfEditorDeclarationPatter.matcher(text);
            while (matcher.find()) {
                String spanTag = matcher.group();
                if (spanTag.contains("display:none")) {
                    text = matcher.replaceFirst("<span style=\"display:none\">");
                } else {
                    text = matcher.replaceFirst("<span>");
                }
                matcher.reset(text);
            }
            while (!removeNoOpSpanTags(text).equals(text)) {
                text = removeNoOpSpanTags(text);
            }
        }

        return text;

    } catch (WGException e) {
        throw new FormattingException("Exception on RTF-Encoding", e);
    }
}

From source file:org.springframework.data.hadoop.store.strategy.naming.RollingFileNamingStrategy.java

@Override
public Path init(Path path) {
    path = super.init(path);
    log.debug("Initialising from path=" + path);
    if (path != null) {
        String name = path.getName();

        // find numeric part
        Pattern counterPattern = Pattern.compile(prefix + "(" + "\\d+" + ")");
        Matcher m = counterPattern.matcher(name);
        while (m.find()) {
            counter = Integer.parseInt(m.group(1)) + 1;
        }/*from w  w w . j  ava 2 s  .co  m*/
        log.debug("Initialized counter starting from " + counter);

        // find complete part handled by this strategy
        Pattern replacePattern = Pattern.compile("(" + prefix + "\\d+" + ")(.*)");
        m = replacePattern.matcher(name);

        // remove a rolling part
        name = m.replaceFirst("$2");
        if (StringUtils.hasText(name)) {
            path = new Path(path.getParent(), name);
            log.debug("Removed handled prefix, path is now " + path);
        } else {
            path = null;
            log.debug("Removed last handled name part, returning null");
        }
    }
    return path;
}