记录IO流和正则的使用
- 查找替换小说目录名
- 注意:
- Matcher对象调用group()之前要先调用find();
- Pattern regexStr = Pattern.compile(regex) // regex正则规则;
- Matcher matcher =regexStr.matcher(strLine) // strLine 为待匹配的字符串;
- 问题:为什么调group()之前必须调用fine(),否则会发生java.lang.IllegalStateException: No match found异常。
解答:查看文档发现有“如果匹配成功可以通过start,end和group方法来获得,然后更多的信息”。意思就是调用find()才匹配,并不是调用之前(如创建对象的时候)匹配。
4.** 代码中分组一使用 s 始终匹配不成功,原理还没有弄清楚**; - 代码:
import java.io.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class TestMain {
public static void main(String[] args) {
long timeStar = System.currentTimeMillis();
String fileName = "C:\Users\Yu\Desktop\";
String regex = "( )([廿卅一二三四五六七八九十]+)、(.{0,6})"; //[廿卅一二三四五六七八九十]+、[dD]+
Pattern regexStr = Pattern.compile(regex);
Matcher matcher = null;
// 转换流
InputStreamReader isr = null;
OutputStreamWriter osw = null;
// 缓冲流
BufferedReader br = null;
BufferedWriter bw = null;
// 字节流
FileInputStream fis = null;
FileOutputStream fos = null;
String strLine = null;
try {
// 输入流
fis = new FileInputStream(fileName+"sunshine.txt");
isr = new InputStreamReader(fis,"gbk");
br = new BufferedReader(isr);
// 输出流
fos = new FileOutputStream(fileName+"doneSunshine.txt");
osw = new OutputStreamWriter(fos,"gbk");
bw = new BufferedWriter(osw);
while ((strLine = br.readLine()) != null){
matcher = regexStr.matcher(strLine);
if (matcher.find()){
String group = matcher.group(2);
group = "第"+group+"章";
strLine = "t"+group+" "+matcher.group(3);
}
bw.write(strLine);
bw.newLine();
}
} catch (Exception e) {
e.printStackTrace();
}finally {
if(br!=null){
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(isr!=null){
try {
isr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(fis!=null){
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(bw!=null){
try {
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(osw!=null){
try {
osw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(fos!=null){
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
System.out.println(System.currentTimeMillis()-timeStar);
}
}