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:org.codelibs.fess.web.IndexAction.java

protected boolean hasFieldInQuery(final Set<String> fieldSet, final String query) {
    final Matcher matcher = FIELD_EXTRACTION_PATTERN.matcher(query);
    if (matcher.matches()) {
        final String field = matcher.replaceFirst("$1");
        if (fieldSet.contains(field)) {
            return true;
        }/* ww  w  .j  a va 2 s.  c o  m*/
        fieldSet.add(field);
    }
    return false;
}

From source file:org.jahia.services.templates.ModuleBuildHelper.java

private List<String> convertToNativeEncoding(List<String> sourceContent, Charset charset)
        throws UnsupportedEncodingException {
    List<String> targetContent = new ArrayList<String>();
    for (String s : sourceContent) {
        Matcher m = UNICODE_PATTERN.matcher(s);
        int start = 0;
        while (m.find(start)) {
            String replacement = new String(new byte[] { (byte) Integer.parseInt(m.group(1), 16),
                    (byte) Integer.parseInt(m.group(2), 16) }, "UTF-16");
            if (charset.decode(charset.encode(replacement)).toString().equals(replacement)) {
                s = m.replaceFirst(replacement);
            }//from  ww  w. ja  v a 2s  . com
            start = m.start() + 1;
            m = UNICODE_PATTERN.matcher(s);
        }
        targetContent.add(s);
    }
    return targetContent;
}

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

public HashMap<String, String> _renderQA(Object[] data, List<String> args) {
    // data is [cid, nid, mid, did, ord, tags, flds]
    // unpack fields and create dict
    String[] flist = Utils.splitFields((String) data[6]);
    Map<String, String> fields = new HashMap<String, String>();
    long modelId = (Long) data[2];
    JSONObject model = mModels.get(modelId);
    Map<String, Pair<Integer, JSONObject>> fmap = mModels.fieldMap(model);
    for (String fname : fmap.keySet()) {
        fields.put(fname, flist[fmap.get(fname).first]);
    }/*from  w  w  w.j a v a 2s  .c o m*/
    fields.put("Tags", ((String) data[5]).trim());
    try {
        fields.put("Type", (String) model.get("name"));
        fields.put("Deck", mDecks.name((Long) data[3]));
        JSONObject template;
        if (model.getInt("type") == Sched.MODEL_STD) {
            template = model.getJSONArray("tmpls").getJSONObject((Integer) data[4]);
        } else {
            template = model.getJSONArray("tmpls").getJSONObject(0);
        }
        fields.put("Card", template.getString("name"));
        fields.put("c" + (((Integer) data[4]) + 1), "1");

        // render q & a
        HashMap<String, String> d = new HashMap<String, String>();
        try {
            d.put("id", Long.toString((Long) data[0]));
            String qfmt = template.getString("qfmt");
            String afmt = template.getString("afmt");
            String html;
            String format;

            // runFilter mungeFields for type "q"
            Models.fieldParser fparser = new Models.fieldParser(fields);
            Matcher m = fClozePattern.matcher(qfmt);
            format = m.replaceFirst(String.format(Locale.US, "{{cq:%d:", ((Integer) data[4]) + 1));
            m = fAltClozePattern.matcher(format);
            format = m.replaceFirst(String.format(Locale.US, "<%%cq:%d:", ((Integer) data[4]) + 1));
            html = mModels.getCmpldTemplate(format).execute(fparser);
            html = (String) AnkiDroidApp.getHooks().runFilter("mungeQA", html, "q", fields, model, data, this);
            d.put("q", html);
            // empty cloze?
            if (model.getInt("type") == Sched.MODEL_CLOZE) {
                if (getModels()._availClozeOrds(model, (String) data[6], false).size() == 0) {
                    d.put("q", "Please edit this note and add some cloze deletions.");
                }
            }
            fields.put("FrontSide", mMedia.stripAudio(d.get("q")));

            // runFilter mungeFields for type "a"
            fparser = new Models.fieldParser(fields);
            m = fClozePattern.matcher(afmt);
            format = m.replaceFirst(String.format(Locale.US, "{{ca:%d:", ((Integer) data[4]) + 1));
            m = fAltClozePattern.matcher(format);
            format = m.replaceFirst(String.format(Locale.US, "<%%ca:%d:", ((Integer) data[4]) + 1));
            html = mModels.getCmpldTemplate(format).execute(fparser);
            html = (String) AnkiDroidApp.getHooks().runFilter("mungeQA", html, "a", fields, model, data, this);
            d.put("a", html);
            // empty cloze?
            if (model.getInt("type") == Sched.MODEL_CLOZE) {
                if (getModels()._availClozeOrds(model, (String) data[6], false).size() == 0) {
                    d.put("q",
                            AnkiDroidApp.getAppResources().getString(
                                    com.hichinaschool.flashcards.anki.R.string.empty_cloze_warning,
                                    "<a href=" + HELP_SITE + "#cloze>"
                                            + AnkiDroidApp.getAppResources().getString(
                                                    com.hichinaschool.flashcards.anki.R.string.help_cloze)
                                            + "</a>"));
                }
            }
        } catch (MustacheException e) {
            Resources res = AnkiDroidApp.getAppResources();

            String templateError = String.format(TEMPLATE_ERROR, res.getString(R.string.template_error),
                    res.getString(R.string.template_error_detail), e.getMessage(),
                    res.getString(R.string.note_type), model.getString("name"),
                    res.getString(R.string.card_type), template.getString("name"),
                    res.getString(R.string.template_error_fix));
            d.put("q", templateError);
            d.put("a", templateError);
        }

        return d;
    } catch (JSONException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.nit.libanki.Collection.java

public HashMap<String, String> _renderQA(Object[] data, List<String> args) {
    // data is [cid, nid, mid, did, ord, tags, flds]
    // unpack fields and create dict
    String[] flist = Utils.splitFields((String) data[6]);
    Map<String, String> fields = new HashMap<String, String>();
    long modelId = (Long) data[2];
    JSONObject model = mModels.get(modelId);
    Map<String, Pair<Integer, JSONObject>> fmap = mModels.fieldMap(model);
    for (String fname : fmap.keySet()) {
        fields.put(fname, flist[fmap.get(fname).first]);
    }/*  w  w  w  .  ja va  2s  .  co  m*/
    fields.put("Tags", ((String) data[5]).trim());
    try {
        fields.put("Type", (String) model.get("name"));
        fields.put("Deck", mDecks.name((Long) data[3]));
        JSONObject template;
        if (model.getInt("type") == Sched.MODEL_STD) {
            template = model.getJSONArray("tmpls").getJSONObject((Integer) data[4]);
        } else {
            template = model.getJSONArray("tmpls").getJSONObject(0);
        }
        fields.put("Card", template.getString("name"));
        fields.put("c" + (((Integer) data[4]) + 1), "1");

        // render q & a
        HashMap<String, String> d = new HashMap<String, String>();
        try {
            d.put("id", Long.toString((Long) data[0]));
            String qfmt = template.getString("qfmt");
            String afmt = template.getString("afmt");
            String html;
            String format;

            // runFilter mungeFields for type "q"
            Models.fieldParser fparser = new Models.fieldParser(fields);
            Matcher m = fClozePattern.matcher(qfmt);
            format = m.replaceFirst(String.format(Locale.US, "{{cq:%d:", ((Integer) data[4]) + 1));
            m = fAltClozePattern.matcher(format);
            format = m.replaceFirst(String.format(Locale.US, "<%%cq:%d:", ((Integer) data[4]) + 1));
            html = mModels.getCmpldTemplate(format).execute(fparser);
            html = (String) AnkiDroidApp.getHooks().runFilter("mungeQA", html, "q", fields, model, data, this);
            d.put("q", html);
            // empty cloze?
            if (model.getInt("type") == Sched.MODEL_CLOZE) {
                if (getModels()._availClozeOrds(model, (String) data[6], false).size() == 0) {
                    d.put("q", "Please edit this note and add some cloze deletions.");
                }
            }
            fields.put("FrontSide", mMedia.stripAudio(d.get("q")));

            // runFilter mungeFields for type "a"
            fparser = new Models.fieldParser(fields);
            m = fClozePattern.matcher(afmt);
            format = m.replaceFirst(String.format(Locale.US, "{{ca:%d:", ((Integer) data[4]) + 1));
            m = fAltClozePattern.matcher(format);
            format = m.replaceFirst(String.format(Locale.US, "<%%ca:%d:", ((Integer) data[4]) + 1));
            html = mModels.getCmpldTemplate(format).execute(fparser);
            html = (String) AnkiDroidApp.getHooks().runFilter("mungeQA", html, "a", fields, model, data, this);
            d.put("a", html);
            // empty cloze?
            if (model.getInt("type") == Sched.MODEL_CLOZE) {
                if (getModels()._availClozeOrds(model, (String) data[6], false).size() == 0) {
                    d.put("q",
                            AnkiDroidApp.getAppResources()
                                    .getString(com.nit.vicky.R.string.empty_cloze_warning,
                                            "<a href="
                                                    + HELP_SITE + "#cloze>" + AnkiDroidApp.getAppResources()
                                                            .getString(com.nit.vicky.R.string.help_cloze)
                                                    + "</a>"));
                }
            }
        } catch (MustacheException e) {
            Resources res = AnkiDroidApp.getAppResources();

            String templateError = String.format(TEMPLATE_ERROR, res.getString(R.string.template_error),
                    res.getString(R.string.template_error_detail), e.getMessage(),
                    res.getString(R.string.note_type), model.getString("name"),
                    res.getString(R.string.card_type), template.getString("name"),
                    res.getString(R.string.template_error_fix));
            d.put("q", templateError);
            d.put("a", templateError);
        }

        return d;
    } catch (JSONException e) {
        throw new RuntimeException(e);
    }
}

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 w w w.  ja  v  a2s. c om*/
            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:dev.memento.MementoBrowser.java

/**
 * Change IA URLs back to their original.
 * //from  w  w w . ja v a2  s .co m
 * Example of IA URLs: 
 * 
 * http://www.foo.org.wstub.archive.org/links.html
 * http://web.archive.org/web/20071222090517/http://www.foo.org/
 * http://web.archive.org/web/20070127071850rn_1/www.harding.edu/USER/fmccown/WWW/
 */
private String convertIaUrlBack(String iaUrl) {
    String url = iaUrl;

    url = url.replace(".wstub.archive.org", "");

    String pattern = "^http://web.archive.org/.+\\d{14}.*?/";

    // Create a Pattern object
    Pattern r = Pattern.compile(pattern);

    // Now create matcher object.
    Matcher m = r.matcher(iaUrl);
    if (m.find()) {
        System.out.println("Found value: " + m.group(0));
        url = m.replaceFirst("");
    }

    if (!url.startsWith("http://") && !url.startsWith("https://"))
        url = "http://" + url;

    return url;
}

From source file:org.exoplatform.clouddrive.box.BoxAPI.java

/**
 * Correct file link for enterprise users with the enterprise custom domain (if it present).
 * /*from  w  w w .jav  a 2 s .  co m*/
 * @param fileLink {@link String}
 * @return file link optionally with added custom domain.
 */
private String link(String fileLink) {
    if (customDomain != null) {
        Matcher m = BOX_URL_MAKE_CUSTOM_PATTERN.matcher(fileLink);
        if (m.matches()) {
            // we need add custom domain to the link host name
            return m.replaceFirst("$1://" + customDomain + ".$2");
        } // else, link already starts with custom domain (actual for Enterprise users)
    } // else, custom domain not available

    return fileLink;
}

From source file:org.cloudifysource.esc.driver.provisioning.privateEc2.PrivateEC2CloudifyDriver.java

private String replaceProperties(final File file, final File propertiesFile) throws IOException {
    logger.fine("Properties file=" + propertiesFile.getName());
    final Properties props = new Properties();
    props.load(new FileInputStream(propertiesFile));

    String templateString = FileUtils.readFileToString(file);

    final Pattern p = Pattern.compile(PATTERN_PROPS_JSON);
    Matcher m = p.matcher(templateString);
    while (m.find()) {
        final String group = m.group();
        final String group1 = m.group(1);
        if (props.containsKey(group1)) {
            final String value = props.getProperty(group1);
            if (logger.isLoggable(Level.FINEST)) {
                logger.finest("Replacing property " + group + " by " + value);
            }/*from ww  w. ja  v  a2s  .com*/
            templateString = m.replaceFirst(group.replace(group1, value));
            m = p.matcher(templateString);
        } else {
            throw new IllegalStateException("Couldn't find property: " + group1);
        }
    }
    return templateString;
}

From source file:org.oscarehr.casemgmt.service.CaseManagementManager.java

/**
 * Substitute for updateCurrentIssueToCPP we replace old issue with new without clobbering existing text
 **/// w ww  .  j  a  v  a  2s  .  co  m
public void changeIssueInCPP(String demoNo, String origIssueDesc, String newIssueDesc) {
    CaseManagementCPP cpp = caseManagementCPPDAO.getCPP(demoNo);
    if (cpp == null) {
        logger.error("Cannot change issue: No CPP found for demographic: " + demoNo);
        return;
    }
    String ongoing = cpp.getOngoingConcerns();
    String newOngoing;

    Pattern pattern = Pattern.compile("^" + origIssueDesc + "$", Pattern.MULTILINE);
    Matcher matcher = pattern.matcher(ongoing);

    if (matcher.find()) {
        newOngoing = matcher.replaceFirst(newIssueDesc);
        cpp.setOngoingConcerns(newOngoing);
        caseManagementCPPDAO.saveCPP(cpp);

        OscarProperties properties = OscarProperties.getInstance();
        if (!Boolean.parseBoolean(properties.getProperty("AbandonOldChart", "false"))) {
            echartDAO.updateEchartOngoing(cpp);
        }
    }

}

From source file:org.oscarehr.casemgmt.service.CaseManagementManager.java

/**
 * substitute function for updateCurrentIssueToCPP We don't want to clobber existing text in ongoing concerns all we want to do is remove the issue description
 **///from  w w w .j a v  a  2s  .  c o m
public void removeIssueFromCPP(String demoNo, CaseManagementIssue issue) {
    CaseManagementCPP cpp = caseManagementCPPDAO.getCPP(demoNo);
    if (cpp == null) {
        logger.error("Cannot remove issue: No CPP found for demographic: " + demoNo);
        return;
    }

    String ongoing = cpp.getOngoingConcerns();
    String newOngoing;
    String description;

    description = issue.getIssue().getDescription();
    Pattern pattern = Pattern.compile("^" + description + "$", Pattern.MULTILINE);
    Matcher matcher = pattern.matcher(ongoing);

    if (matcher.find()) {
        newOngoing = matcher.replaceFirst("");

        cpp.setOngoingConcerns(newOngoing);
        caseManagementCPPDAO.saveCPP(cpp);

        OscarProperties properties = OscarProperties.getInstance();
        if (!Boolean.parseBoolean(properties.getProperty("AbandonOldChart", "false"))) {
            echartDAO.updateEchartOngoing(cpp);
        }
    }
}