對於在職場工作的朋友們如果需要批量提取文本信息就可以使用本方法
1 import java.io.BufferedReader; 2 import java.io.BufferedWriter; 3 import java.io.File; 4 import java.io.FileReader; 5 import java.io.FileWriter; 6 import java.io.IOException; 7 import java.util.regex.Matcher; 8 import java.util.regex.Pattern; 9 10 public class TextExtract { 11 public static void main(String[] args) throws IOException { 12 File f = new File("in.txt"); 13 File out = new File("out.txt"); 14 Pattern pattern = Pattern.compile("your regex"); 15 BufferedReader br = new BufferedReader(new FileReader(f)); 16 BufferedWriter bw = new BufferedWriter(new FileWriter(out)); 17 String s = null; 18 while((s = br.readLine())!=null){ 19 Matcher matcher = pattern.matcher(s); 20 while(matcher.find()){ 21 bw.write(matcher.group()); 22 bw.newLine(); 23 } 24 //bw.newLine();寫入換行 25 bw.flush(); 26 } 27 } 28 }
in.txt是輸入文本,out.txt是輸出文本,your regex就是你的正則表達式,文本路徑可以使用相對路徑,也可以使用絕對路徑
除了使用代碼以外,博主再給大家推薦一個十分好用的正則文本提取工具,使用正則的同時還支持自定義假則
下面附上鏈接:
鏈接:https://share.weiyun.com/5mppBs3 密碼:p65p63
還有正則表達式測試工具(免費的)
鏈接:https://share.weiyun.com/5pFGVxB 密碼:5bvfps
最后再附上正則表達式快速入門教程