⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 replaceregexp.java

📁 Use the links below to download a source distribution of Ant from one of our mirrors. It is good pra
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
    /**     * A substitution pattern.  You can use this element to refer to a previously     * defined substitution pattern datatype instance.     * @return the substitution pattern object to be configured as an element     */    public Substitution createSubstitution() {        if (subs != null) {            throw new BuildException("Only one substitution expression is "                                     + "allowed");        }        subs = new Substitution();        return subs;    }    /**     * Invoke a regular expression (r) on a string (input) using     * substitutions (s) for a matching regex.     *     * @param r a regular expression     * @param s a Substitution     * @param input the string to do the replacement on     * @param options The options for the regular expression     * @return the replacement result     */    protected String doReplace(RegularExpression r,                               Substitution s,                               String input,                               int options) {        String res = input;        Regexp regexp = r.getRegexp(getProject());        if (regexp.matches(input, options)) {            log("Found match; substituting", Project.MSG_DEBUG);            res = regexp.substitute(input, s.getExpression(getProject()),                                    options);        }        return res;    }    /**     *  Perform the replacement on a file     *     * @param f the file to perform the relacement on     * @param options the regular expressions options     * @exception IOException if an error occurs     */    protected void doReplace(File f, int options)         throws IOException {        File temp = FILE_UTILS.createTempFile("replace", ".txt", null, true, true);        Reader r = null;        Writer w = null;        try {            if (encoding == null) {                r = new FileReader(f);                w = new FileWriter(temp);            } else {                r = new InputStreamReader(new FileInputStream(f), encoding);                w = new OutputStreamWriter(new FileOutputStream(temp),                                           encoding);            }            BufferedReader br = new BufferedReader(r);            BufferedWriter bw = new BufferedWriter(w);            PrintWriter pw = new PrintWriter(bw);            boolean changes = false;            log("Replacing pattern '" + regex.getPattern(getProject())                + "' with '" + subs.getExpression(getProject())                + "' in '" + f.getPath() + "'" + (byline ? " by line" : "")                + (flags.length() > 0 ? " with flags: '" + flags + "'" : "")                + ".", Project.MSG_VERBOSE);            if (byline) {                StringBuffer linebuf = new StringBuffer();                String line = null;                String res = null;                int c;                boolean hasCR = false;                do {                    c = br.read();                    if (c == '\r') {                        if (hasCR) {                            // second CR -> EOL + possibly empty line                            line = linebuf.toString();                            res  = doReplace(regex, subs, line, options);                            if (!res.equals(line)) {                                changes = true;                            }                            pw.print(res);                            pw.print('\r');                            linebuf = new StringBuffer();                            // hasCR is still true (for the second one)                        } else {                            // first CR in this line                            hasCR = true;                        }                    } else if (c == '\n') {                        // LF -> EOL                        line = linebuf.toString();                        res  = doReplace(regex, subs, line, options);                        if (!res.equals(line)) {                            changes = true;                        }                        pw.print(res);                        if (hasCR) {                            pw.print('\r');                            hasCR = false;                        }                        pw.print('\n');                        linebuf = new StringBuffer();                    } else { // any other char                        if ((hasCR) || (c < 0)) {                            // Mac-style linebreak or EOF (or both)                            line = linebuf.toString();                            res  = doReplace(regex, subs, line, options);                            if (!res.equals(line)) {                                changes = true;                            }                            pw.print(res);                            if (hasCR) {                                pw.print('\r');                                hasCR = false;                            }                            linebuf = new StringBuffer();                        }                        if (c >= 0) {                            linebuf.append((char) c);                        }                    }                } while (c >= 0);                pw.flush();            } else {                String buf = FileUtils.safeReadFully(br);                String res = doReplace(regex, subs, buf, options);                if (!res.equals(buf)) {                    changes = true;                }                pw.print(res);                pw.flush();            }            r.close();            r = null;            w.close();            w = null;            if (changes) {                log("File has changed; saving the updated file", Project.MSG_VERBOSE);                try {                    FILE_UTILS.rename(temp, f);                    temp = null;                } catch (IOException e) {                    throw new BuildException("Couldn't rename temporary file "                                             + temp, getLocation());                }            } else {                log("No change made", Project.MSG_DEBUG);            }        } finally {            FileUtils.close(r);            FileUtils.close(w);            if (temp != null) {                temp.delete();            }        }    }    /**     * Execute the task     *     * @throws BuildException is there is a problem in the task execution.     */    public void execute() throws BuildException {        if (regex == null) {            throw new BuildException("No expression to match.");        }        if (subs == null) {            throw new BuildException("Nothing to replace expression with.");        }        if (file != null && filesets.size() > 0) {            throw new BuildException("You cannot supply the 'file' attribute "                                     + "and filesets at the same time.");        }        int options = 0;        if (flags.indexOf('g') != -1) {            options |= Regexp.REPLACE_ALL;        }        if (flags.indexOf('i') != -1) {            options |= Regexp.MATCH_CASE_INSENSITIVE;        }        if (flags.indexOf('m') != -1) {            options |= Regexp.MATCH_MULTILINE;        }        if (flags.indexOf('s') != -1) {            options |= Regexp.MATCH_SINGLELINE;        }        if (file != null && file.exists()) {            try {                doReplace(file, options);            } catch (IOException e) {                log("An error occurred processing file: '"                    + file.getAbsolutePath() + "': " + e.toString(),                    Project.MSG_ERR);            }        } else if (file != null) {            log("The following file is missing: '"                + file.getAbsolutePath() + "'", Project.MSG_ERR);        }        int sz = filesets.size();        for (int i = 0; i < sz; i++) {            FileSet fs = (FileSet) (filesets.elementAt(i));            DirectoryScanner ds = fs.getDirectoryScanner(getProject());            String[] files = ds.getIncludedFiles();            for (int j = 0; j < files.length; j++) {                File f = new File(fs.getDir(getProject()), files[j]);                if (f.exists()) {                    try {                        doReplace(f, options);                    } catch (Exception e) {                        log("An error occurred processing file: '"                            + f.getAbsolutePath() + "': " + e.toString(),                            Project.MSG_ERR);                    }                } else {                    log("The following file is missing: '"                        + f.getAbsolutePath() + "'", Project.MSG_ERR);                }            }        }    }}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -