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:io.stallion.dataAccess.file.TextFilePersister.java

public T fromString(String fileContent, Path fullPath) {
    if (fullPath.toString().endsWith(".html") || fullPath.toString().endsWith(".htm")) {
        return fromHtml(fileContent, fullPath);
    }/*  ww  w  .j a va 2  s.c  o m*/
    String relativePath = fullPath.toString().replace(getBucketFolderPath(), "");
    Path path = fullPath;

    T item = null;
    try {
        item = getModelClass().newInstance();
    } catch (InstantiationException e) {
        throw new RuntimeException(e);
    } catch (IllegalAccessException e) {
        throw new RuntimeException(e);
    }
    item.setTags(new ArrayList<String>()).setElementById(new HashMap<>()).setElements(new ArrayList<>())
            .setPublishDate(ZonedDateTime.of(LocalDateTime.now(), ZoneId.of("UTC"))).setTitle("")
            .setDraft(false).setTemplate("").setContent("").setSlug("");

    /* Get the id and slug */

    item.setSlug(FilenameUtils.removeExtension(relativePath));
    if (!item.getSlug().startsWith("/")) {
        item.setSlug("/" + item.getSlug());
    }
    if (item.getSlug().endsWith("/index")) {
        item.setSlug(item.getSlug().substring(item.getSlug().length() - 6));
    }

    if (empty(fileContent.trim())) {
        return item;
    }

    /* Parse out toml properties, if found */
    String tomlContent;
    Matcher tomlMatcher = tomlPattern.matcher(fileContent);
    if (tomlMatcher.find()) {
        tomlContent = tomlMatcher.group(1).trim();
        fileContent = tomlMatcher.replaceAll("\n");
        Map tomlMap = new Toml().read(tomlContent).to(HashMap.class);
        for (Object key : tomlMap.keySet()) {
            Object value = tomlMap.get(key);
            setProperty(item, key.toString(), value);
        }
    }

    List<String> allLines = Arrays.asList(fileContent.split("\n"));

    if (allLines.size() == 0) {
        return item;
    }

    if (empty(item.getTitle())) {
        item.setTitle(allLines.get(0));
    }

    String titleLine = "";
    List<String> propertiesSection = list();
    String rawContent = "";
    int propertiesStartAt = 0;
    if (allLines.size() > 1) {
        if (allLines.get(1).startsWith("----") || allLines.get(1).startsWith("====")) {
            titleLine = allLines.get(0);
            propertiesStartAt = 2;
            item.setTitle(titleLine);
        }
    }

    int propertiesEndAt = propertiesStartAt;
    for (; propertiesEndAt < allLines.size(); propertiesEndAt++) {
        String line = allLines.get(propertiesEndAt);
        if (line.trim().equals("---")) {
            continue;
        }
        int colon = line.indexOf(':');
        if (colon == -1) {
            break;
        }
        String key = line.substring(0, colon).trim();
        String value = line.substring(colon + 1, line.length()).trim();
        if ("oldUrls".equals(key)) {
            setProperty(item, key, apply(list(StringUtils.split(value, ";")), (aUrl) -> aUrl.trim()));
        } else {
            setProperty(item, key, value);
        }
    }
    if (propertiesEndAt < allLines.size()) {
        rawContent = StringUtils.join(allLines.subList(propertiesEndAt, allLines.size()), "\n").trim();
    }

    Boolean isMarkdown = false;
    if (path.toString().toLowerCase().endsWith(".txt") || path.toString().toLowerCase().endsWith(".md")) {
        isMarkdown = true;
    }
    item.setElements(StElementParser.parseElements(rawContent, isMarkdown));
    List<StElement> items = item.getElements();
    for (StElement ele : items) {
        item.getElementById().put(ele.getId(), ele);
    }

    String itemContent = StElementParser.removeTags(rawContent).trim();
    item.setOriginalContent(itemContent);

    if (isMarkdown) {
        Log.fine("Parse for page {0} {1} {2}", item.getId(), item.getSlug(), item.getTitle());
        String cacheKey = DigestUtils.md5Hex("markdown-to-html" + Literals.GSEP + itemContent);
        String cached = null;
        if (!"test".equals(Settings.instance().getEnv())) {
            cached = PermaCache.get(cacheKey);
        }
        if (cached == null) {
            itemContent = Markdown.instance().process(itemContent);
            PermaCache.set(cacheKey, itemContent);
        } else {
            itemContent = cached;
        }

        item.setContent(itemContent);
    }

    if (empty(item.getId())) {
        item.setId(makeIdFromFilePath(relativePath));
    }

    Log.fine("Loaded text item: id:{0} slug:{1} title:{2} draft:{3}", item.getId(), item.getSlug(),
            item.getTitle(), item.getDraft());
    return item;
}

From source file:org.dspace.app.bulkedit.DSpaceCSV.java

/**
 * Set the value separator for multiple values stored in one csv value.
 *
 * Is set in bulkedit.cfg as valueseparator
 *
 * If not set, defaults to double pipe '||'
 *//*from  w  w w  . java2  s  .c  om*/
private void setValueSeparator() {
    // Get the value separator
    valueSeparator = DSpaceServicesFactory.getInstance().getConfigurationService()
            .getProperty("bulkedit.valueseparator");
    if ((valueSeparator != null) && (!"".equals(valueSeparator.trim()))) {
        valueSeparator = valueSeparator.trim();
    } else {
        valueSeparator = "||";
    }

    // Now store the escaped version
    Pattern spchars = Pattern.compile("([\\\\*+\\[\\](){}\\$.?\\^|])");
    Matcher match = spchars.matcher(valueSeparator);
    escapedValueSeparator = match.replaceAll("\\\\$1");
}

From source file:com.rks.musicx.misc.utils.Helper.java

/**
 * Filter String/*w  w w.  j av a 2s.co m*/
 *
 * @param str
 * @return
 */
public static String stringFilter(String str) {
    if (str == null) {
        return null;
    }
    Pattern lineMatcher = Pattern.compile("\\n[\\\\/:*?\\\"<>|]((\\[\\d\\d:\\d\\d\\.\\d\\d\\])+)(.+)");
    Matcher m = lineMatcher.matcher(str);
    return m.replaceAll("").trim();
}

From source file:org.dspace.app.bulkedit.DSpaceCSV.java

/**
* Set the authority separator for value with authority data.
*
* Is set in dspace.cfg as bulkedit.authorityseparator
*
* If not set, defaults to double colon '::'
*///  ww w.  ja  v  a2 s  .com
private void setAuthoritySeparator() {
    // Get the value separator
    authoritySeparator = DSpaceServicesFactory.getInstance().getConfigurationService()
            .getProperty("bulkedit.authorityseparator");
    if ((authoritySeparator != null) && (!"".equals(authoritySeparator.trim()))) {
        authoritySeparator = authoritySeparator.trim();
    } else {
        authoritySeparator = "::";
    }

    // Now store the escaped version
    Pattern spchars = Pattern.compile("([\\\\*+\\[\\](){}\\$.?\\^|])");
    Matcher match = spchars.matcher(authoritySeparator);
    escapedAuthoritySeparator = match.replaceAll("\\\\$1");
}

From source file:org.dspace.app.bulkedit.DSpaceCSV.java

/**
 * Set the field separator use to separate fields in the csv.
 *
 * Is set in bulkedit.cfg as fieldseparator
 *
 * If not set, defaults to comma ','.//from  w ww .j a  va2  s. c o m
 *
 * Special values are 'tab', 'hash' and 'semicolon' which will
 * get substituted from the text to the value.
 */
private void setFieldSeparator() {
    // Get the value separator
    fieldSeparator = DSpaceServicesFactory.getInstance().getConfigurationService()
            .getProperty("bulkedit.fieldseparator");
    if ((fieldSeparator != null) && (!"".equals(fieldSeparator.trim()))) {
        fieldSeparator = fieldSeparator.trim();
        if ("tab".equals(fieldSeparator)) {
            fieldSeparator = "\t";
        } else if ("semicolon".equals(fieldSeparator)) {
            fieldSeparator = ";";
        } else if ("hash".equals(fieldSeparator)) {
            fieldSeparator = "#";
        } else {
            fieldSeparator = fieldSeparator.trim();
        }
    } else {
        fieldSeparator = ",";
    }

    // Now store the escaped version
    Pattern spchars = Pattern.compile("([\\\\*+\\[\\](){}\\$.?\\^|])");
    Matcher match = spchars.matcher(fieldSeparator);
    escapedFieldSeparator = match.replaceAll("\\\\$1");
}

From source file:com.screenslicer.core.util.Util.java

public static List<String> transformUrlStrings(List<String> urls, UrlTransform[] urlTransforms,
        boolean forExport) {
    List<String> newUrls = new ArrayList<String>();
    if (urlTransforms != null && urlTransforms.length != 0 && urls != null) {
        for (String url : urls) {
            String newUrl = url;//from  ww w .  j  a v a2  s  .  c o m
            for (int i = 0; urlTransforms != null && i < urlTransforms.length; i++) {
                if (!CommonUtil.isEmpty(urlTransforms[i].regex) && newUrl != null && urlTransforms[i] != null
                        && ((forExport && urlTransforms[i].transformForExportOnly)
                                || (!forExport && !urlTransforms[i].transformForExportOnly))) {
                    Pattern pattern = Pattern.compile(urlTransforms[i].regex,
                            Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CHARACTER_CLASS);
                    Matcher matcher = pattern.matcher(newUrl);
                    if (matcher.find()) {
                        if (urlTransforms[i].replaceAll) {
                            if (urlTransforms[i].replaceAllRecursive) {
                                String transformed = matcher.replaceAll(urlTransforms[i].replacement);
                                String transformedRec = pattern.matcher(transformed)
                                        .replaceAll(urlTransforms[i].replacement);
                                while (!transformed.equals(transformedRec)) {
                                    transformed = transformedRec;
                                    transformedRec = pattern.matcher(transformedRec)
                                            .replaceAll(urlTransforms[i].replacement);
                                }
                                newUrl = transformed;
                            } else {
                                newUrl = matcher.replaceAll(urlTransforms[i].replacement);
                            }
                        } else {
                            newUrl = matcher.replaceFirst(urlTransforms[i].replacement);
                        }
                        if (!urlTransforms[i].multipleTransforms) {
                            break;
                        }
                    }
                }
            }
            newUrls.add(newUrl);
        }
    } else {
        return urls;
    }
    return newUrls;
}

From source file:com.jsmartframework.web.manager.FilterControl.java

private String completeVersions(HttpServletRequest httpRequest, String html) {
    if (versionFilePatterns.isEmpty()) {
        return html;
    }//from  w  w w  . j  a v a2s . co  m
    for (String version : versionFilePatterns.keySet()) {
        Pattern filePattern = versionFilePatterns.get(version);
        Matcher fileMatcher = filePattern.matcher(html);
        html = fileMatcher.replaceAll("$1" + Matcher.quoteReplacement("?" + version));
    }
    return html;
}

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

public String stripAudio(String txt) {
    Matcher m = fSoundRegexps.matcher(txt);
    return m.replaceAll("");
}

From source file:org.auraframework.http.AuraTestFilter.java

private String captureResponse(ServletRequest req, ServletResponse res, String testName, String uri)
        throws ServletException, IOException {
    CapturingResponseWrapper responseWrapper = new CapturingResponseWrapper((HttpServletResponse) res) {
        @Override/*ww w . j  a  v  a  2  s.c om*/
        public void sendRedirect(String location) throws IOException {
            // If the response is redirected after this filter, we want to
            // handle the redirect, so we need to set the jstestrun
            // parameter to make sure we can see it on the next request.
            Matcher test = jstestToRunPattern.matcher(location);
            if (test.find()) {
                location = test.replaceAll(testName);
            } else {
                location = location + (location.indexOf('?') < 0 ? "?" : "&") + jstestToRun.name + "="
                        + testName;
            }
            super.sendRedirect(location);
        }
    };
    RequestDispatcher dispatcher = req.getServletContext().getContext(uri).getRequestDispatcher(uri);
    if (dispatcher == null) {
        return null;
    }
    dispatcher.forward(req, responseWrapper);
    if (responseWrapper.getRedirectUrl() != null) {
        return null;
    }
    return responseWrapper.getCapturedResponseString();
}