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.apache.maven.plugin.cxx.CMakeMojo.java

protected void updateOrCreateCMakeDependenciesFile(List aiDependenciesLib, boolean bMavenDependencies) {
    String dependencieFile = (bMavenDependencies ? cmakeMavenDependenciesFile : cmakeDependenciesFile);
    String fullDependenciesFile = dependencieFile;
    File file = new File(dependencieFile);
    if (!file.isAbsolute()) {
        // $FB always use unix path separator with cmake even under windows !
        fullDependenciesFile = getProjectDir() + "/" + dependencieFile;
    }//from www. j  av  a 2  s. com
    file = new File(fullDependenciesFile);

    if (!file.exists()) {
        try {
            file.createNewFile();
        } catch (IOException e) {
            getLog().error(dependencieFile + " script can't be created at " + file.getAbsolutePath());
            return;
        }
    }

    // check file content
    InputStream dependenciesStream = null;
    String content = new String();
    try {
        dependenciesStream = new FileInputStream(file);
        content = IOUtils.toString(dependenciesStream, "UTF8");
    } catch (IOException e) {
        // shall not happen since file has been created
        getLog().error(dependencieFile + " script can't be opened at " + file.getAbsolutePath());
    } finally {
        getLog().debug("close input stream at reading");
        IOUtils.closeQuietly(dependenciesStream);
    }

    String beginDepsPattern = (bMavenDependencies
            ? (isDebugBuild() ? "# BEGIN MAVEN_DEBUG_DEPENDENCIES" : "# BEGIN MAVEN_OPTIMIZED_DEPENDENCIES")
            : "# BEGIN CMAKE_DEPENDENCIES");
    String endDepsPattern = (bMavenDependencies
            ? (isDebugBuild() ? "# END MAVEN_DEBUG_DEPENDENCIES" : "# END MAVEN_OPTIMIZED_DEPENDENCIES")
            : "# END CMAKE_DEPENDENCIES");

    String beginIncPattern = "# BEGIN MAVEN_INCLUDE_ROOTS";
    String endIncPattern = "# END MAVEN_INCLUDE_ROOTS";

    // reset file content if needed
    if (StringUtils.isEmpty(content) || content.indexOf(beginDepsPattern) == -1) {
        getLog().info(file.getAbsolutePath() + " content full update");
        try {
            dependenciesStream = getClass()
                    .getResourceAsStream((bMavenDependencies ? "/cmake-cpp-project/CMakeMavenDependencies.txt"
                            : "/cmake-cpp-project/CMakeDependencies.txt"));
            content = IOUtils.toString(dependenciesStream, "UTF8");
        } catch (IOException e) {
            getLog().error(dependencieFile + " default content not found ");
        } finally {
            getLog().debug("close input stream at full update");
            IOUtils.closeQuietly(dependenciesStream);
        }
    }

    // update file content
    String simpleIndentation = "\n    ";
    String doubleIndentation = "\n        ";
    Iterator itDeps = aiDependenciesLib.iterator();
    StringBuilder allDepsBuilder = new StringBuilder(
            (bMavenDependencies ? doubleIndentation : simpleIndentation));
    while (itDeps.hasNext()) {
        String dep = (String) itDeps.next();
        if (bMavenDependencies) {
            String externalDep = generalizeDependencyFileName(dep, true);
            allDepsBuilder.append("target_link_libraries(${target} "
                    + (isDebugBuild() ? "debug " : "optimized ") + externalDep + ")" + doubleIndentation);
        } else {
            String cmakeDep = generalizeDependencyFileName(dep, false);
            allDepsBuilder.append("# If a \"" + cmakeDep
                    + "\" target has been define, this means we are building " + "an amalgamed cmake project"
                    + simpleIndentation + "# but maven dependencies can be used too" + simpleIndentation
                    + "if(TARGET " + cmakeDep + ")" + doubleIndentation + "message(\"Adding direct " + cmakeDep
                    + " cmake dependencies to target '${target}'\")" + doubleIndentation
                    + "target_link_libraries(${target} " + cmakeDep + ")" + simpleIndentation + "endif()"
                    + simpleIndentation);
        }
    }

    // adding additionalIncludeRoots in cmake maven dependencies file
    StringBuilder addIncsBuilder = new StringBuilder(doubleIndentation);
    if (bMavenDependencies && null != additionalIncludeRoots) {
        addIncsBuilder.append("include_directories( " + doubleIndentation);
        for (String includeRoot : additionalIncludeRoots) {
            addIncsBuilder.append("\"" + includeRoot + "\"" + doubleIndentation);
        }
        addIncsBuilder.append(")" + doubleIndentation);
        for (String includeRoot : additionalIncludeRoots) {
            addIncsBuilder.append(
                    "message(\"Adding '" + includeRoot + "' additional include root.\")" + doubleIndentation);
        }
    }

    getLog().debug(dependencieFile + " depfile was : " + content);
    String allDeps = Matcher.quoteReplacement(allDepsBuilder.toString());
    //.replace( "$", "\\$" ); // Matcher replaceAll() is a bit rigid !
    getLog().debug(dependencieFile + " injected dependency will be : " + allDeps);
    // regexp multi-line replace, see http://stackoverflow.com/questions/4154239/java-regex-replaceall-multiline
    Pattern p1 = Pattern.compile(beginDepsPattern + ".*" + endDepsPattern, Pattern.DOTALL);
    Matcher m1 = p1.matcher(content);
    content = m1.replaceAll(beginDepsPattern + allDeps + endDepsPattern);

    if (bMavenDependencies && null != additionalIncludeRoots) {
        String addIncs = Matcher.quoteReplacement(addIncsBuilder.toString());
        //.replace( "$", "\\$" ); // Matcher replaceAll() is a bit rigid !
        getLog().debug(dependencieFile + " injected includes Roots will be : " + addIncs);
        Pattern p2 = Pattern.compile(beginIncPattern + ".*" + endIncPattern, Pattern.DOTALL);
        Matcher m2 = p2.matcher(content);
        content = m2.replaceAll(beginIncPattern + addIncs + endIncPattern);
    }

    getLog().debug(dependencieFile + " depfile now is : " + content);
    OutputStream outStream = null;
    try {
        outStream = new FileOutputStream(file);
        IOUtils.write(content, outStream, "UTF8");
    } catch (IOException e) {
        getLog().error(
                dependencieFile + " script can't be written at " + file.getAbsolutePath() + e.toString());
    } finally {
        getLog().debug("close output stream at update");
        IOUtils.closeQuietly(outStream);
    }
}

From source file:org.apache.tika.eval.AbstractProfiler.java

/**
 *
 * @param metadata//w w w  . j a  v  a  2s  . c o m
 * @param extracts
 * @return evalfilepaths for files if crawling an extract directory
 */
protected EvalFilePaths getPathsFromExtractCrawl(Metadata metadata, Path extracts) {
    String relExtractFilePath = metadata.get(FSProperties.FS_REL_PATH);
    Matcher m = FILE_NAME_CLEANER.matcher(relExtractFilePath);
    Path relativeSourceFilePath = Paths.get(m.replaceAll(""));
    //just try slapping the relextractfilepath on the extractdir
    Path extractFile = extracts.resolve(relExtractFilePath);
    if (!Files.isRegularFile(extractFile)) {
        //if that doesn't work, try to find the right extract file.
        //This is necessary if crawling extractsA and trying to find a file in
        //extractsB that is not in the same format: json vs txt or compressed
        extractFile = findFile(extracts, relativeSourceFilePath);
    }
    return new EvalFilePaths(relativeSourceFilePath, extractFile);
}

From source file:com.wecandoit.jinju_0_0_4.jActivity_YoutubeSearchList.java

@Override
public boolean onQueryTextSubmit(String query) {
    jG.Log.d("onQueryTextSubmit = " + query);

    Pattern pattern = Pattern.compile("\\s+");
    Matcher matcher = pattern.matcher(query);
    String decodedSearchStr = matcher.replaceAll("%20");

    String searchUrl = SEARCH_URL_1 + decodedSearchStr + SEARCH_URL_2;

    new jGetterVideoListFromYouTube().execute(searchUrl);

    return true;//from  w  ww.  j  a  va 2  s .co m
}

From source file:com.hichinaschool.flashcards.libanki.Media.java

/**
 * Strips a string from media references.
 * //  ww  w.j  ava2 s  . co m
 * @param txt The string to be cleared of media references.
 * @return The media-free string.
 */
public String strip(String txt) {
    Matcher m = null;
    for (Pattern p : fMediaRegexps) {
        m = p.matcher(txt);
        txt = m.replaceAll("");
    }
    return txt;
}

From source file:me.doshou.admin.maintain.staticresource.web.controller.StaticResourceVersionController.java

private StaticResource switchStaticResourceContent(String rootRealPath, String versionedResourceRealPath,
        String fileName, String content, boolean isMin) throws IOException {

    StaticResource resource = extractResource(fileName, content);
    String filePath = resource.getUrl();
    filePath = filePath.replace("${ctx}", rootRealPath);

    if (isMin) {/*ww  w.  j ava  2  s  .  c o m*/
        File file = new File(YuiCompressorUtils.getCompressFileName(filePath));
        if (!file.exists()) {
            throw new RuntimeException("" + resource.getUrl());
        }
    } else {
        File file = new File(YuiCompressorUtils.getNoneCompressFileName(filePath));
        if (!file.exists()) {
            throw new RuntimeException("?" + resource.getUrl());
        }
    }

    content = StringEscapeUtils.unescapeXml(content);

    File file = new File(versionedResourceRealPath + fileName);

    List<String> contents = FileUtils.readLines(file);

    for (int i = 0, l = contents.size(); i < l; i++) {
        String fileContent = contents.get(i);
        if (content.equals(fileContent)) {
            Matcher matcher = scriptPattern.matcher(content);
            if (!matcher.matches()) {
                matcher = linkPattern.matcher(content);
            }
            String newUrl = isMin ? YuiCompressorUtils.getCompressFileName(resource.getUrl())
                    : YuiCompressorUtils.getNoneCompressFileName(resource.getUrl());

            content = matcher.replaceAll("$1" + Matcher.quoteReplacement(newUrl) + "$3$4$5");
            contents.set(i, content);

            resource.setContent(content);
            resource.setUrl(newUrl);

            break;
        }
    }
    FileUtils.writeLines(file, contents);

    return resource;
}

From source file:cn.dockerfoundry.ide.eclipse.dockerfile.validator.DockerfileDelegatingValidator.java

@SuppressWarnings("unchecked")
public Map<DockerfileValidationLevel, List<DockerfileValidationResult>> validate() {
    Map<DockerfileValidationLevel, List<DockerfileValidationResult>> result = new HashMap<DockerfileValidationLevel, List<DockerfileValidationResult>>();
    if (this.dockerfileInputStream == null)
        return result;

    ValidatorUtils validatorUtils = new ValidatorUtils();
    boolean fromCheck = false;
    int currentLine = 0;
    List<DockerfileValidationResult> errors = new ArrayList<DockerfileValidationResult>();
    List<DockerfileValidationResult> warnings = new ArrayList<DockerfileValidationResult>();
    List<DockerfileValidationResult> infos = new ArrayList<DockerfileValidationResult>();

    Map<String, Object> ruleObject = validatorUtils
            .getRules(DockerfileDelegatingValidator.class.getResourceAsStream("default.yaml"));
    List<Map<String, Object>> requiredInstructions = validatorUtils.createReqInstructionHash(ruleObject);
    Map<String, Object> general = (Map<String, Object>) ruleObject.get("general");
    List<String> valid_instructions = (List<String>) general.get("valid_instructions");
    Pattern validInstructionsRegex = validatorUtils.createValidCommandRegex(valid_instructions);
    Pattern continuationRegex = null;
    //      Pattern ignoreRegex = null;
    Object multiline_regex = general.get("multiline_regex");
    if (multiline_regex != null && multiline_regex.toString().length() > 2) {
        String _multiline_regex = multiline_regex.toString().substring(1,
                multiline_regex.toString().length() - 1);
        continuationRegex = Pattern.compile(_multiline_regex, Pattern.CASE_INSENSITIVE);
    }/*from  w w w  . j  a v a 2 s  .  c om*/
    Object ignore_regex = general.get("ignore_regex");
    if (ignore_regex != null && ignore_regex.toString().length() > 2) {
        String _ignore_regex = ignore_regex.toString().substring(1, ignore_regex.toString().length() - 1);
        Pattern ignoreRegex = Pattern.compile(_ignore_regex, Pattern.CASE_INSENSITIVE);
        System.out.println("ignore_regex is not used for now: " + ignoreRegex.pattern());
    }

    try {
        String dockerfile = IOUtils.toString(dockerfileInputStream);
        String[] linesArr = dockerfile.split("(\\r|\\n)");
        if (linesArr != null && linesArr.length > 0) {
            for (int i = 0; i < linesArr.length; i++) {
                currentLine++;
                String line = linesArr[i];
                int lineOffSet = 0;
                if (line == null || line.length() == 0 || line.charAt(0) == '#') {
                    continue;
                }

                while (validatorUtils.isPartialLine(line, continuationRegex)) {
                    line = continuationRegex.matcher(line).replaceAll(" ");
                    if (linesArr[currentLine + lineOffSet].charAt(0) == '#') {
                        linesArr[currentLine + lineOffSet] = null;
                        line = line + "\\";
                    } else {
                        line = line + linesArr[currentLine + lineOffSet];
                        linesArr[currentLine + lineOffSet] = null;
                    }
                    lineOffSet++;
                }

                // First instruction must be FROM
                if (!fromCheck) {
                    fromCheck = true;
                    if (line.toUpperCase().indexOf("FROM") != 0) {
                        DockerfileValidationResult error = new DockerfileValidationResult();
                        error.setLine(currentLine);
                        error.setLevel(DockerfileValidationLevel.ERROR);
                        error.setMessage("Missing or misplaced FROM");
                        error.setLineContent(line);
                        errors.add(error);
                    }
                } // end for FROM

                Matcher matcher = validInstructionsRegex.matcher(line);
                if (!matcher.find()) {
                    DockerfileValidationResult error = new DockerfileValidationResult();
                    error.setLine(currentLine);
                    error.setLevel(DockerfileValidationLevel.ERROR);
                    error.setMessage("Invalid instruction");
                    error.setLineContent(line);
                    errors.add(error);
                } else {
                    String instruction = line.substring(matcher.start(), matcher.end()).trim();
                    String params = matcher.replaceAll("");
                    validatorUtils.checkLineRules(ruleObject, instruction, params, line, currentLine, errors,
                            warnings, infos);
                    requiredInstructions.remove(instruction);
                } // end for valid instructions checking
            }
        }
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    validatorUtils.checkRequiredInstructions(requiredInstructions, errors, warnings, infos);

    result.put(DockerfileValidationLevel.ERROR, errors);
    result.put(DockerfileValidationLevel.WARNING, warnings);
    result.put(DockerfileValidationLevel.INFO, infos);
    return result;
}

From source file:org.apache.roller.weblogger.ui.struts2.editor.WeblogExport.java

/**
 * Performs some pre-processing of entry text. It fixes a problem when
 * WordPress imports a self-closing HTML tag that does not have a space
 * preceding the "/>" characters. It also provides a replacment base URL
 * for all referenced resource files if requested.
 *
 * @param text The entry text to process.
 * @return The resulting String after processing has taken place.
 *//*from w  w w.  j a  v  a2  s .c o  m*/
private String processEntry(String text) {
    String result;
    result = text;

    // Some special processing is needed for mtimport
    if (format.startsWith(MT_FORMAT)) {
        // Fix self closing tags that are missing a space,
        // replaceing <foo bar="foobar"/> with <foo bar="foobar" />
        Matcher badSelfClosingTagMatcher;
        badSelfClosingTagMatcher = SC_TAG_PATTERN.matcher(result);

        result = badSelfClosingTagMatcher.replaceAll("$2 />");

        if (format.equals(MT_PLUS_FORMAT)) {
            // Replace all newlines with spaces leaving "<pre>" blocks
            // alone. WordPress will automatically convert newlines to
            // "<br />" which alters the intended formatting.
            Matcher preTagMatcher;
            preTagMatcher = PRE_TAG_PATTERN.matcher(result);

            StringBuilder replacedNewLines;
            replacedNewLines = new StringBuilder();

            int index;
            index = 0;

            while (preTagMatcher.find()) {
                replacedNewLines.append(NEWLINE_PATTERN.matcher(result.substring(index, preTagMatcher.start()))
                        .replaceAll(" "));
                replacedNewLines.append(preTagMatcher.group());
                index = preTagMatcher.end();
            }

            replacedNewLines
                    .append(NEWLINE_PATTERN.matcher(result.substring(index, result.length())).replaceAll(" "));

            result = replacedNewLines.toString();
        }
    }

    // Replace all /weblog-handle/resource/ links with a specified base URL
    if (baseUrl != null && !baseUrl.equals("")) {
        Matcher baseUrlMatcher;
        baseUrlMatcher = baseUrlPattern.matcher(result);

        try {
            result = baseUrlMatcher.replaceAll("$1" + baseUrl);
        } catch (IllegalArgumentException e) {
            log.error("Invalid base URL submitted: " + baseUrl + ": " + e.getMessage());
        }
    }

    return result;
}

From source file:com.wavemaker.studio.StudioService.java

@ExposeToClient
public Hashtable<String, Object> getLogUpdate(String filename, String lastStamp) throws IOException {
    java.io.File logFolder = new java.io.File(System.getProperty("catalina.home") + "/logs/ProjectLogs",
            this.projectManager.getCurrentProject().getProjectName());
    java.io.File logFile = new java.io.File(logFolder, filename);
    if (!logFile.exists()) {
        Hashtable<String, Object> PEmpty = new Hashtable<String, Object>();
        PEmpty.put(LOG_UPDATE_LOGS, "");
        PEmpty.put(LOG_UPDATE_LAST_STAMP, 0);
        return PEmpty;
    }//from   w w  w.  ja va 2s.c  o m
    InputStream inputStream = new FileInputStream(logFile);
    try {
        String logFileContent = IOUtils.toString(inputStream);
        if (lastStamp.length() > 0) {
            // remove everything up to START_WM_LOG_LINE lastStamp
            Pattern pattern = Pattern.compile("^.*START_WM_LOG_LINE\\s+" + lastStamp + "\\s+", Pattern.DOTALL);
            Matcher matcher = pattern.matcher(logFileContent);
            logFileContent = matcher.replaceFirst("");
            // Replace everything from the start of whats left of this line to END_WM_LOG_LINE
            logFileContent = logFileContent.replaceFirst("^.*?END_WM_LOG_LINE", "");
        }

        Pattern htmlTagPattern = Pattern
                .compile("(START_WM_LOG_LINE\\s+\\d+\\:\\d+\\:\\d+,\\d+\\s+)(\\S+) (\\(.*\\))");
        Matcher htmlTagMatcher = htmlTagPattern.matcher(logFileContent);
        logFileContent = htmlTagMatcher
                .replaceAll("$1<span class='LogType$2'>$2</span> <span class='LogLocation'>$3</span>");

        Pattern p = Pattern.compile("START_WM_LOG_LINE\\s+\\d+\\:\\d+\\:\\d+,\\d+");
        Matcher m = p.matcher(logFileContent);
        String timestamp = "";
        while (m.find()) {
            timestamp = m.group();
            timestamp = timestamp.replaceFirst("START_WM_LOG_LINE\\s+.*?", "");
        }
        Hashtable<String, Object> logUpdate = new Hashtable<String, Object>();
        logFileContent = m.replaceAll(""); // remove all START_WM_LOG_LINE xxx:xxx:xxx,xxx
        logFileContent = logFileContent.replaceAll(" END_WM_LOG_LINE", "");
        if (logFileContent.matches("^\\s+$")) {
            logFileContent = "";
        }
        logFileContent = logFileContent.replaceAll("(\\S+)(\\n\\r|\\r\\n|\\n|\\r)", "$1<br/>");
        Pattern trimPattern = Pattern.compile("^\\s*", Pattern.MULTILINE);
        Matcher trimMatcher = trimPattern.matcher(logFileContent);
        logFileContent = trimMatcher.replaceAll("");
        logUpdate.put(LOG_UPDATE_LOGS, logFileContent);
        logUpdate.put(LOG_UPDATE_LAST_STAMP, timestamp);
        return logUpdate;
    } finally {
        inputStream.close();
    }
}

From source file:com.haulmont.yarg.loaders.impl.JsonDataLoader.java

@Override
public List<Map<String, Object>> loadData(ReportQuery reportQuery, BandData parentBand,
        Map<String, Object> reportParams) {
    Map<String, Object> currentParams = new HashMap<String, Object>();
    if (reportParams != null) {
        currentParams.putAll(reportParams);
    }//from  w ww. java  2  s.  co m

    List<Map<String, Object>> result = new ArrayList<Map<String, Object>>();

    Matcher matcher = parameterPattern.matcher(reportQuery.getScript());
    String parameterName = getParameterName(matcher);

    //adds parameters from parent bands hierarchy
    BandData curentParentBand = parentBand;
    while (curentParentBand != null) {
        addParentBandDataToParameters(curentParentBand, currentParams);
        curentParentBand = curentParentBand.getParentBand();
    }

    if (parameterName != null) {
        Object parameterValue = currentParams.get(parameterName);
        if (parameterValue != null && StringUtils.isNotBlank(parameterValue.toString())) {
            String json = parameterValue.toString();
            String script = matcher.replaceAll("");

            if (StringUtils.isBlank(script)) {
                throw new DataLoadingException(
                        String.format("The script doesn't contain json path expression. " + "Script [%s]",
                                reportQuery.getScript()));
            }

            matcher = AbstractDbDataLoader.COMMON_PARAM_PATTERN.matcher(script);
            while (matcher.find()) {
                String parameter = matcher.group(1);
                script = matcher.replaceAll(String.valueOf(currentParams.get(parameter)));
            }

            try {
                Object scriptResult = JsonPath.read(json, script);
                parseScriptResult(result, script, scriptResult);
            } catch (com.jayway.jsonpath.PathNotFoundException e) {
                return Collections.emptyList();
            } catch (Throwable e) {
                throw new DataLoadingException(String.format(
                        "An error occurred while loading data with script [%s]", reportQuery.getScript()), e);
            }
        } else {
            return Collections.emptyList();
        }
    } else {
        throw new DataLoadingException(String.format(
                "Query string doesn't contain link to parameter. " + "Script [%s]", reportQuery.getScript()));
    }

    return result;
}

From source file:net.longfalcon.newsj.TVRageService.java

private String cleanName(String name) {
    name = name.replace(".", " ");
    name = name.replace("_", " ");
    name = name.replace("&", "and");
    Pattern pattern = Pattern.compile("^(history|discovery) channel", Pattern.CASE_INSENSITIVE);
    Matcher matcher = pattern.matcher(name);
    name = matcher.replaceAll("");

    name = name.replaceAll("(\\\\|:|!|\\\"|#|\\*|'|,|\\(|\\)|\\?)", "");

    pattern = Pattern.compile("\\s{2,}", Pattern.CASE_INSENSITIVE);
    matcher = pattern.matcher(name);//from w  w  w . j a va 2s.c  o  m
    name = matcher.replaceAll(" ");
    return name.trim();
}