什么是正則表達式
正則表達式是一種可以用于模式匹配和替換的規范,一個正則表達式就是由普通的字符(例如字符a到z)以及特殊字符(元字符)組成的文字模式,它 用以描述在查找文字主體時待匹配的一個或多個字符串。正則表達式作為一個模板,將某個字符模式與所搜索的字符串進行匹配。
Java利用正則表達式提取數據
Java正則表達式的用途很廣,之前要用到將一大 3M 的 txt 文本切分成多個小文本,用 C# 寫的話很簡潔,代碼也就二十幾行,今天用 Java 寫了一下,果然,Java 很羅嗦。
切分文件的代碼就不貼了,主要貼一下怎么使用正則表達式將大字符串進行分組:
比如,現在有一個 endlist.txt 文本文件,內容如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
|
public static void main(String args[]) { File file = null ; BufferedReader br = null ; StringBuffer buffer = null ; String childPath = "src/endlist.txt" ; String data = "" ; try { file = new File(childPath); buffer = new StringBuffer(); InputStreamReader isr = new InputStreamReader( new FileInputStream(file), "utf-8" ); br = new BufferedReader(isr); int s; while ((s = br.read()) != - 1 ) { buffer.append(( char ) s); } data = buffer.toString(); } catch (Exception e) { e.printStackTrace(); } Map<String, ArrayList<String>> resultMap = new HashMap<String, ArrayList<String>>(); for ( int i = 0 ; i < 10 ; i++) { resultMap.put( "13" + i, new ArrayList<String>()); } Pattern pattern = Pattern.compile( "(\\d{3})(\\d{4},[\u4e00-\u9fa5]*\\n)" ); Matcher matcher = pattern.matcher(data); while (matcher.find()) { resultMap.get(matcher.group( 1 )).add(matcher.group( 2 )); } for ( int i = 0 ; i < 10 ; i++) { if (resultMap.get( "13" + i).size() > 0 ) { try { File outFile = new File( "src/13" + i + ".txt" ); FileOutputStream outputStream = new FileOutputStream(outFile); OutputStreamWriter writer = new OutputStreamWriter(outputStream, "utf-8" ); ArrayList<String> tempList = resultMap.get( "13" + i); for ( int j = 0 ; j < tempList.size(); j++) { writer.append(resultMap.get( "13" + i).get(j)); } writer.close(); outputStream.close(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } |
第24行使用正則表達式 "(\\d{3})(\\d{4},[\u4e00-\u9fa5]*\\n)" 每個()中的內容為一組,索引從 1 開始,0表示整個表達式。所以這個表達式分為兩組,第一組表示3個數字,第二組表示 4個數字加多個漢字加一個換行符。提取時如26-28行所示。
總結
以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作能帶來一定的幫助,如果有疑問大家可以留言交流。