如何在文件內容中使用正則表達式。我有一組文件,我想在所有文件中搜索一個字符串並替換所有文件。java在文件內容中的正則表達式
有人可以幫我嗎?如下:
package com.java.far;
import java.io.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ReplaceAll {
public static void main(String[] args)throws IOException {
Runtime r=Runtime.getRuntime();
System.out.println(r.freeMemory());
String path="D:\\JOBRELATED\\FAR";
String files;
File folder=new File(path);
File[] listofFiles=folder.listFiles();
for (int i = 0; i < listofFiles.length; i++) {
if (listofFiles[i].isFile()) {
files=listofFiles[i].getName();
if(files.endsWith("tex")){
System.out.println(files);
BufferedReader br=new BufferedReader(new FileReader("D:\\JOBRELATED\\FAR\\"+files));
String line;
while((line=br.readLine())!=null){
Pattern p=Pattern.compile("Diamond in History and Research");
Matcher m=p.matcher(line);
int count=0;
while (m.find()) {
count++;
//System.out.println(m.start() +"\t"+ count);
System.out.println(line);
m.replaceAll("abc");
}
}
}
}
}
}
}
是沒可能只使用'sed'?啊......看起來像你在Windows上。 – Nishant 2012-08-09 05:26:52
請注意,正則表達式不適用於大文件。正則表達式本質上是遞歸的,在使用正則表達式處理大塊數據時,會出現StackOverflow異常。 – 2012-08-09 06:09:13