package liao.learn.string;
import java.io.BufferedReader;
import java.io.CharArrayWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* _正则表达式和IO
* @author A555
*
*/
public class Regex {
public static void main(String[] args) {
// 1.读取文件
File file = new File("F:/QQ下载/MobileFile/大王饶命.txt");
try {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(file),"utf-8"));
CharArrayWriter arrayWriter = new CharArrayWriter();
String line = null; // 需要替换的行
// 2.以行为单位进行遍历
while((line = bufferedReader.readLine()) != null){
String regex = "[0-9]{1,4}、"; // 正则表达式 匹配需要修改的字符,也可固定字符
String replacement = ""; // 需要替换的字符
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(line);
if(matcher.find()){ // 存在匹配的字符
System.out.println("Found value: " + matcher.group(0) );
replacement = "第"+matcher.group(0).substring(0, matcher.group(0).length()-1)+"章 "; // 得到匹配的字符,修改为需要的字符
System.out.println("repalce value: " + replacement);
}
line = line.replaceAll(regex, replacement); // 替换每一行中符合被替换字符条件的字符串,regex 也可修改-matcher.group(0)
arrayWriter.write(line); // 将该行写入内存
arrayWriter.append(System.getProperty("line.separator")); //添加换行符,并进入下次循环
}
//关闭输入流
bufferedReader.close();
//将内存中的流写入源文件
FileWriter fw=new FileWriter(file);
arrayWriter.writeTo(fw);
fw.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}