replaceAll()正则表达式

benh 2008-02-25 03:34:08
想把文件的所有行号去掉,例如0021: ,就是4个数字+冒号,replaceAll的参数该怎么表示呢?
...全文
407 9 打赏 收藏 转发到动态 举报
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
  • 打赏
  • 举报
回复
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.Closeable;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Test {

public static void main(String[] args) {
BufferedReader br = null;
BufferedWriter bw = null;
try {
Pattern pattern = Pattern.compile("(?m)^[ \t]*\\d{4}:[ \t]*");
String line = System.getProperty("line.separator");
br = new BufferedReader(new FileReader("1.txt"));
bw = new BufferedWriter(new FileWriter("1_.txt"));
String str = null;
while((str = br.readLine())!=null) {
str = replace(pattern, str);
bw.write(str + line);
}
}catch(IOException e) {
e.printStackTrace();
}finally{
close(bw);
close(br);
}
System.out.println("finished.");
}

private static String replace(Pattern pattern, String str) {
Matcher matcher = pattern.matcher(str);
return matcher.replaceAll("");
}

private static void close(Closeable closeable) {
if(closeable != null) {
try {
closeable.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}


文件内容

0001: Line 1, 0001: Line 1
0002: Line 2, 0002: Line 2
0003: Line 3, 0003: Line 3
0004: Line 4, 0004: Line 4
  • 打赏
  • 举报
回复
行号前面是否有空格?冒号后面的空格是否需要去掉等等之类的说明一下,这样写出的正则表达式才能有用武之地。
logi22 2008-02-25
  • 打赏
  • 举报
回复
不用正则的话,System.out.println(str.substring(5));
用的话,System.out.println(str.replaceAll("\\d{4}:",""));
你得少了个\
benh 2008-02-25
  • 打赏
  • 举报
回复
用 string.replaceAll("\d{4}:" , ""); , 提示invalid escape sequence, 怎么回事?
yami251139 2008-02-25
  • 打赏
  • 举报
回复
比如用substring()切一下或者split()之類的。。。
又不是驗證 干什么非要正則啊。。。
yangxiao_jiang 2008-02-25
  • 打赏
  • 举报
回复
\d{4}:
yami251139 2008-02-25
  • 打赏
  • 举报
回复
覺得沒什么必要用正則的。。。除非你老大要求你這么做。。。
yami251139 2008-02-25
  • 打赏
  • 举报
回复
是全部都是這種格式?
那 ^[0-9][0-9][0-9][0-9]\:$
先把0021:拿出來和他match一下 然后true的話就replace
healer_kx 2008-02-25
  • 打赏
  • 举报
回复
这种情况不用正则。手工写,格式这么整齐,用正则属于浪费。

62,614

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧