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:at.ac.tuwien.inso.subcat.utility.commentparser.Parser.java

License:asdf

private void parseQuotes(List<ContentNode<T>> ast, String comment) {
    Matcher m = pQuote.matcher(comment);

    int lastEnd = 0;
    while (m.find()) {
        if (lastEnd >= 0 && lastEnd != m.start()) {
            parseParagraphs(ast, comment.substring(lastEnd, m.start()));
        }//  w w  w  .ja v a2 s . co  m

        String content = m.group(0);
        String idStr = m.group(2);
        int id = (idStr != null) ? Integer.parseInt(idStr) : -1;

        Matcher cfm = pCleanFstQuote.matcher(content);
        content = cfm.replaceAll("");

        Matcher csm = pCleanSubQuote.matcher(content);
        content = csm.replaceAll("");

        String[] contentFragments = pQuoteSplitter.split(content.trim());
        String[] cleanedFragments = new String[contentFragments.length];
        for (int i = 0; i < contentFragments.length; i++) {
            Matcher normM = pNorm.matcher(contentFragments[i]);
            cleanedFragments[i] = normM.replaceAll(" ");
        }

        ast.add(new QuoteNode<T>(cleanedFragments, id));
        lastEnd = m.end();
    }

    if (lastEnd != comment.length()) {
        String frag = comment.substring(lastEnd, comment.length());
        if (frag.trim().length() > 0) {
            parseGLibMessages(ast, frag);
        }
    }
}

From source file:de.escidoc.core.test.aa.StatisticReaderIT.java

/**
 * triggers preprocessing./*ww w  .  j  a v  a  2  s  .com*/
 *
 * @param methodIndex methodIndex
 * @throws Exception If anything fails.
 */
private void triggerPreprocessing(final String methodIndex) throws Exception {
    String urlParameters = PREPROCESSING_URL + System.currentTimeMillis();

    Matcher methodIndexMatcher = METHOD_INDEX_PATTERN.matcher(urlParameters);
    urlParameters = methodIndexMatcher.replaceAll(methodIndex);

    String httpUrl = getFrameworkUrl() + Constants.ESCIDOC_BASE_URI + urlParameters;
    long time = System.currentTimeMillis();
    HttpResponse httpRes = HttpHelper.executeHttpRequest(null, Constants.HTTP_METHOD_GET, httpUrl, null, null,
            null);
    String response = EntityUtils.toString(httpRes.getEntity(), HTTP.UTF_8);
    httpRes.getEntity().consumeContent();
    response = " preprocessing needed " + (System.currentTimeMillis() - time) + response;
    try {
        assertMatches("String does not match es expected. " + response,
                "Operation completed successfully without a return value", response);

    } catch (final AssertionError e) {
        if (methodIndex.equals(STATISTIC_PREPROCESSR_METHOD_INDEX)) {
            triggerPreprocessing("1");
        } else {
            throw e;
        }
    }
}

From source file:com.meidusa.venus.validate.validator.ValidatorSupport.java

public void setMessage(String message) {
    List<String> messageParams = new ArrayList<String>();
    Matcher matcher = pattern.matcher(message);
    while (matcher.find()) {
        messageParams.add(matcher.group(1));
    }/*from   ww  w  . j a  v  a2  s.c o m*/
    this.messageParameters = (String[]) messageParams.toArray(new String[] {});
    this.message = matcher.replaceAll("%s");
}

From source file:appeng.recipes.loader.RecipeResourceCopier.java

/**
 * List directory contents for a resource folder. Not recursive. This is basically a brute-force implementation. Works for regular files and also JARs.
 *
 * @param clazz Any java class that lives in the same place as the resources you want.
 * @param path Should end with "/", but not start with one.
 *
 * @return Just the name of each member item, not the full paths.
 *
 * @throws URISyntaxException            if it is a file path and the URL can not be converted to URI
 * @throws IOException                   if jar path can not be decoded
 * @throws UnsupportedOperationException if it is neither in jar nor in file path
 *///from   w  w w .j  a  v  a2 s  .  c  o  m
@Nonnull
private String[] getResourceListing(@Nonnull final Class<?> clazz, @Nonnull final String path)
        throws URISyntaxException, IOException {
    assert clazz != null;
    assert path != null;

    final ClassLoader classLoader = clazz.getClassLoader();
    if (classLoader == null) {
        throw new IllegalStateException(
                "ClassLoader was not found. It was probably loaded at a inappropriate time");
    }

    URL dirURL = classLoader.getResource(path);
    if (dirURL != null) {
        final String protocol = dirURL.getProtocol();
        if (protocol.equals(FILE_PROTOCOL)) {
            // A file path: easy enough

            final URI uriOfURL = dirURL.toURI();
            final File fileOfURI = new File(uriOfURL);
            final String[] filesAndDirectoriesOfURI = fileOfURI.list();

            if (filesAndDirectoriesOfURI == null) {
                throw new IllegalStateException(
                        "Files and Directories were illegal. Either an abstract pathname does not denote a directory, or an I/O error occured.");
            } else {
                return filesAndDirectoriesOfURI;
            }
        }
    }

    if (dirURL == null) {
        /*
         * In case of a jar file, we can't actually find a directory.
         * Have to assume the same jar as clazz.
         */
        final String className = clazz.getName();
        final Matcher matcher = DOT_COMPILE_PATTERN.matcher(className);
        final String me = matcher.replaceAll("/") + CLASS_EXTENSION;
        dirURL = classLoader.getResource(me);
    }

    if (dirURL != null) {
        final String protocol = dirURL.getProtocol();
        if (protocol.equals(JAR_PROTOCOL)) {
            /* A JAR path */
            final String dirPath = dirURL.getPath();
            final String jarPath = dirPath.substring(5, dirPath.indexOf('!')); // strip out only
            // the JAR file
            final JarFile jar = new JarFile(URLDecoder.decode(jarPath, UTF_8_ENCODING));
            try {
                final Enumeration<JarEntry> entries = jar.entries(); // gives ALL entries in jar
                final Collection<String> result = new HashSet<String>(INITIAL_RESOURCE_CAPACITY); // avoid duplicates

                // in case it is a
                // subdirectory
                while (entries.hasMoreElements()) {
                    final JarEntry entry = entries.nextElement();
                    final String entryFullName = entry.getName();
                    if (entryFullName.startsWith(path)) { // filter according to the path
                        String entryName = entryFullName.substring(path.length());
                        final int checkSubDir = entryName.indexOf('/');
                        if (checkSubDir >= 0) {
                            // if it is a subdirectory, we just return the directory name
                            entryName = entryName.substring(0, checkSubDir);
                        }
                        result.add(entryName);
                    }
                }

                return result.toArray(new String[result.size()]);
            } finally {
                jar.close();
            }
        }
    }

    throw new UnsupportedOperationException("Cannot list files for URL " + dirURL);
}

From source file:org.apache.roller.weblogger.ui.rendering.model.UtilitiesModel.java

private String replace(String string, Pattern pattern, String replacement) {
    Matcher m = pattern.matcher(string);
    return m.replaceAll(replacement);
}

From source file:info.xuluan.podcast.SearchActivity.java

public String getUrl() {
    String prefix = "http://lfe-alpo-gm.appspot.com/search?q=";
    String suffix = "";
    String str = SearchActivity.this.mEditText.getText().toString();

    Pattern pattern = Pattern.compile("^\\s+");
    Matcher matcher = pattern.matcher(str);

    str = matcher.replaceAll("");

    pattern = Pattern.compile("\\s+$");
    matcher = pattern.matcher(str);//from   w w  w  .  j  a  v a2s  .c o  m

    str = matcher.replaceAll("");

    pattern = Pattern.compile("\\s+");
    matcher = pattern.matcher(str);

    str = matcher.replaceAll("+");
    log.debug("query string = " + str);
    if (str.length() > 0)
        return prefix + str + suffix;

    return null;
}

From source file:org.craftercms.studio.impl.v1.service.dependency.RegexDependencyResolver.java

@Override
public Map<String, Set<String>> resolve(String site, String path) {
    Map<String, Set<String>> toRet = new HashMap<String, Set<String>>();
    try {/* w  ww . j  a v a 2 s.c  om*/
        DependencyResolverConfigTO config = getConfiguraion(site);
        if (config != null) {
            String content = contentService.getContentAsString(site, path);
            if (content != null) {
                Map<String, DependencyResolverConfigTO.ItemType> itemTypes = config.getItemTypes();
                if (itemTypes != null) {
                    for (Map.Entry<String, DependencyResolverConfigTO.ItemType> entry : itemTypes.entrySet()) {
                        DependencyResolverConfigTO.ItemType itemType = entry.getValue();
                        List<String> includes = itemType.getIncludes();
                        if (ContentUtils.matchesPatterns(path, includes)) {
                            Map<String, DependencyResolverConfigTO.DependencyType> dependencyTypes = itemType
                                    .getDependencyTypes();
                            for (Map.Entry<String, DependencyResolverConfigTO.DependencyType> dependencyTypeEntry : dependencyTypes
                                    .entrySet()) {
                                Set<String> extractedPaths = new HashSet<String>();
                                DependencyResolverConfigTO.DependencyType dependencyType = dependencyTypeEntry
                                        .getValue();
                                List<DependencyResolverConfigTO.DependencyExtractionPattern> extractionPatterns = dependencyType
                                        .getIncludes();
                                for (DependencyResolverConfigTO.DependencyExtractionPattern extractionPattern : extractionPatterns) {
                                    Pattern pattern = Pattern.compile(extractionPattern.getFindRegex());
                                    Matcher matcher = pattern.matcher(content);
                                    while (matcher.find()) {
                                        String matchedPath = matcher.group();
                                        if (CollectionUtils.isNotEmpty(extractionPattern.getTransforms())) {
                                            for (DependencyResolverConfigTO.DependencyExtractionTransform transform : extractionPattern
                                                    .getTransforms()) {
                                                Pattern find = Pattern.compile(transform.getMatch());
                                                Matcher replaceMatcher = find.matcher(matchedPath);
                                                matchedPath = replaceMatcher.replaceAll(transform.getReplace());
                                            }
                                        }
                                        if (contentService.contentExists(site, matchedPath)) {
                                            extractedPaths.add(matchedPath);
                                        } else {
                                            String message = "Found reference to " + matchedPath
                                                    + " in content at " + path
                                                    + " but content does not exist in referenced path for site "
                                                    + site + ".\n"
                                                    + "Regular expression for extracting dependencies matched "
                                                    + "string, and after applying transformation rules to get value "
                                                    + "for dependency path, that dependency path was not found in"
                                                    + " site repository as a content.";
                                            logger.debug(message);
                                        }
                                    }
                                }
                                toRet.put(dependencyType.getName(), extractedPaths);
                            }
                        }
                    }
                }
            } else {
                logger.error("Failed to extract dependencies. Content not found for site: " + site + ", path: "
                        + path);
            }
        } else {
            String configLocation = getConfigLocation(site);
            logger.error("Failed to load Dependency Resolver configuration. Verify that configuration exists"
                    + " and it is valid XML file: " + configLocation);
        }
    } catch (Exception exc) {
        logger.error("Unexcpected error resolving dependencies for site: " + site + " path: " + path);
    }
    return toRet;
}

From source file:au.org.ala.bhl.TaxonGrab.java

private void analyse(String word, Set<String> lexicon, SearchState state) {
    if (!pat_symbols.matcher(word).find()) {
        Matcher m = pat_bracket_w.matcher(word);
        if (m.find()) {
            word = m.replaceAll("");
        }//from   ww  w  .  j  av  a  2  s.com

        String wordKey = pat_punct_rem.matcher(word).replaceAll("").toLowerCase();

        if (!StringUtils.isEmpty(state.CurrentFullName) && pat_var_sub.matcher(wordKey).find()) {
            state.Taxa.push(state.CurrentFullName + " " + word);
            state.CurrentFullName = null;
        }

        // if the word is contained in the lexicon it is discarded

        if (!lexicon.contains(normalizeText(wordKey, ACCENTS))) {

            if (pat_fam.matcher(word).find() && !pat_vs.matcher(word).find()) {
                state.F_Word = word;
                state.S_Word = "";
            } else if (!StringUtils.isEmpty(state.F_Word) && StringUtils.isEmpty(state.S_Word)) {
                word = word.replace(",", "");
                if (pat_spec.matcher(word).find()) {
                    state.S_Word = word;
                    state.Taxa.push(state.F_Word + " " + state.S_Word);
                } else if (pat_subgen.matcher(word).find()) {
                    state.S_Word = word;
                } else {
                    state.S_Word = state.F_Word = null;
                }
            } else if (!StringUtils.isEmpty(state.F_Word) && !StringUtils.isEmpty(state.S_Word)
                    && word.length() > 2) {
                word = word.replace(",", "");
                if (pat_var_spec.matcher(word).find()) {
                    if (state.Taxa.size() > 0) {
                        state.Taxa.pop();
                    }

                    if (par_subvar.matcher(word).find()) {
                        state.CurrentFullName = state.F_Word + " " + state.S_Word + " " + word;
                    } else if (!pat_dot.matcher(word).find()) {
                        state.Taxa.push(state.F_Word + " " + state.S_Word + " " + word);
                    }
                }
                state.F_Word = state.S_Word = null;
            } else {
                state.F_Word = state.S_Word = null;
            }

        } else {
            state.F_Word = state.S_Word = null;
        }

    } else {
        state.F_Word = state.S_Word = state.CurrentFullName = null;
    }
}

From source file:com.chinamobile.bcbsp.sync.SuperStepCommand.java

public SuperStepCommand(String s) {
    String[] infos = s.split("@");
    if (infos.length == 2) {
        this.migrateStaffIDs = infos[1];
    }/*from w  w  w  .  jav a 2s. c  om*/
    if (infos.length == 3) {
        this.migrateVertexCommand = new MigrateVertexCommand();
        this.migrateVertexCommand.fromString(infos[2]);
    }
    String[] tmp = infos[0].split(Constants.SSC_SPLIT_FLAG);
    int length = tmp.length;
    int index = 0;
    if (length < 6) {
    } else {
        this.commandType = Integer.valueOf(tmp[index++]);
        this.initWritePath = tmp[index++];
        this.initReadPath = tmp[index++];
        this.ableCheckPoint = Integer.valueOf(tmp[index++]);
        this.nextSuperStepNum = Integer.valueOf(tmp[index++]);
        this.oldCheckPoint = Integer.valueOf(tmp[index++]);
    }
    LOG.info("[SuperStepCommand]--[index]" + index);
    LOG.info("[SuperStepCommand]--[CommandType]" + this.commandType);
    if (this.commandType == Constants.COMMAND_TYPE.START_AND_RECOVERY || !this.migrateStaffIDs.equals("")) {
        String str = tmp[index++];
        LOG.info("[SuperStepCommand]--[routeString]" + str);
        String regEx = "[\\{\\}]";
        Pattern p = Pattern.compile(regEx);
        Matcher m = p.matcher(str);
        str = m.replaceAll("");
        str = str.replace(" ", "");
        this.partitionToWorkerManagerNameAndPort = new HashMap<Integer, String>();
        String[] strMap = str.split(",");
        for (int i = 0; i < strMap.length; i++) {
            String[] strKV = strMap[i].split("=");
            if (strKV.length == 2) {
                this.partitionToWorkerManagerNameAndPort.put(Integer.parseInt(strKV[0]), strKV[1]);
            } else {
                continue;
            }
        }
    }
    if (index < length) {
        int count = length - index;
        this.aggValues = new String[count];
        for (int i = 0; i < count; i++) {
            this.aggValues[i] = tmp[index++];
        }
    }
}

From source file:org.apereo.services.persondir.support.jdbc.AbstractJdbcPersonAttributeDao.java

@Override
protected List<IPersonAttributes> getPeopleForQuery(final PartialWhereClause queryBuilder,
        final String queryUserName) {
    //Execute the query
    final RowMapper<R> rowMapper = this.getRowMapper();

    final List<R> results;
    if (queryBuilder != null) {
        //Merge the generated SQL with the base query template
        final StringBuilder partialSqlWhere = queryBuilder.sql;
        final Matcher queryMatcher = WHERE_PLACEHOLDER.matcher(this.queryTemplate);
        final String querySQL = queryMatcher.replaceAll(partialSqlWhere.toString());

        results = this.simpleJdbcTemplate.query(querySQL, rowMapper, queryBuilder.arguments.toArray());

        if (this.logger.isDebugEnabled()) {
            this.logger.debug("Executed '" + this.queryTemplate + "' with arguments " + queryBuilder.arguments
                    + " and got results " + results);
        }/*from   ww w. ja v  a2  s .c o m*/
    } else {
        results = this.simpleJdbcTemplate.query(this.queryTemplate, rowMapper);

        if (this.logger.isDebugEnabled()) {
            this.logger.debug("Executed '" + this.queryTemplate + "' and got results " + results);
        }
    }

    return this.parseAttributeMapFromResults(results, queryUserName);
}