Java正則表達式的用途很廣,之前要用到將一大 3M 的 txt 文本切分成多個小文本,用 C# 寫的話很簡潔,代碼也就二十幾行,今天用 Java 寫了一下,果然,Java 很羅嗦。
切分文件的代碼就不貼了,主要貼一下怎么使用正則表達式將大字符串進行分組:
比如,現在有一個 endlist.txt 文本文件,內容如下:
1300102,北京市 1300103,北京市 1300104,北京市 1300105,北京市 1300106,北京市 1300107,北京市 1300108,北京市 1300109,北京市 1300110,北京市 1300111,北京市 1300112,北京市 1300113,北京市 1300114,北京市 1300115,北京市 1300116,北京市 1300117,北京市 1300118,北京市 1300119,北京市
七位數字代表手機號碼的前七位,后面的漢字表示號碼歸屬地。現在我要將這些內容按照 130 131 132... 開頭分別寫到 130.txt 131.txt 132.txt.....這些文件中。
1 public static void main(String args[]) { 2 File file = null; 3 BufferedReader br = null; 4 StringBuffer buffer = null; 5 String childPath = "src/endlist.txt"; 6 String data = ""; 7 try { 8 file = new File(childPath); 9 buffer = new StringBuffer(); 10 InputStreamReader isr = new InputStreamReader(new FileInputStream(file), "utf-8"); 11 br = new BufferedReader(isr); 12 int s; 13 while ((s = br.read()) != -1) { 14 buffer.append((char) s); 15 } 16 data = buffer.toString(); 17 } catch (Exception e) { 18 e.printStackTrace(); 19 } 20 Map<String, ArrayList<String>> resultMap = new HashMap<String, ArrayList<String>>(); 21 for (int i = 0; i < 10; i++) { 22 resultMap.put("13" + i, new ArrayList<String>()); 23 } 24 Pattern pattern = Pattern.compile("(\\d{3})(\\d{4},[\u4e00-\u9fa5]*\\n)"); 25 Matcher matcher = pattern.matcher(data); 26 while (matcher.find()) { 27 resultMap.get(matcher.group(1)).add(matcher.group(2)); 28 } 29 for (int i = 0; i < 10; i++) { 30 if (resultMap.get("13" + i).size() > 0) { 31 try { 32 File outFile = new File("src/13" + i + ".txt"); 33 FileOutputStream outputStream = new FileOutputStream(outFile); 34 OutputStreamWriter writer = new OutputStreamWriter(outputStream, "utf-8"); 35 ArrayList<String> tempList = resultMap.get("13" + i); 36 for (int j = 0; j < tempList.size(); j++) { 37 writer.append(resultMap.get("13" + i).get(j)); 38 } 39 writer.close(); 40 outputStream.close(); 41 } catch (Exception e) { 42 // TODO Auto-generated catch block 43 e.printStackTrace(); 44 } 45 } 46 } 47 }
第24行使用正則表達式 "(\\d{3})(\\d{4},[\u4e00-\u9fa5]*\\n)" 每個()中的內容為一組,索引從 1 開始,0表示整個表達式。所以這個表達式分為兩組,第一組表示3個數字,第二組表示 4個數字加多個漢字加一個換行符。提取時如26-28行所示。
可能代碼能夠更加簡潔,希望網友們能夠指點。
