2014/07/10

[Java] 正規表達式範例




正規表達式筆記:http://goo.gl/vcN8vs

正規表達式的判斷要用到下面兩個package

?
1
2
import java.util.regex.Pattern;
import java.util.regex.Matcher;

Step1 . 你要配對的字串
?
1
String s = new String("你要配對的字串");

Step2.  正規表達式
?
1
Pattern p = Pattern.compile("你的正規表達式");

Step 3 . 開始配對
?
1
Matcher m = p.matcher(s);

Step4. methods的合併使用
?
1
2
3
while(m.find()){       //如果在字串裡有找到關鍵字
    System.out.println(s.substring(m.start(), m.end()));
}

Step5. 可搭配Map做字串搜尋,見Example2



以下兩個範例

Example 1 :  用正規表達式做是否為浮點數的判斷。


?
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
import java.util.regex.*;
public class Test1 {
    public static void main(String args[]){
        String[] dataSet1 = {"1","1.1","1.0","0.1","1."
        ,".1","1e1","1.1e2","1.0e2","0.1e9","1.e6",".1e0"};
        String[] dataSet2 = {"..1..","1...2e","e","2e","e2"};
        Pattern pattern = Pattern.compile
        ("^(([0-9]+\\.?[0-9]*)|([0-9]*\\.?[0-9]+))(e?[0-9]+)?$");
        for (int i = 0; i < dataSet1.length; i++) {
            Matcher matcher1 = pattern.matcher(dataSet1[i]);
            if(matcher1.find())
                System.out.println(dataSet1[i]+": true");
            else
                System.out.println(dataSet1[i]+": false");
        }
        for (int i = 0; i < dataSet2.length; i++) {
            Matcher matcher2 = pattern.matcher(dataSet2[i]);
            if(matcher2.find())
                System.out.println(dataSet2[i]+": true");
            else
                System.out.println(dataSet2[i]+": false");
        }
         
    }
}


Example 2:利用正規表達式和HashMap,做一篇文章中不同單字的統計,且利用ArrayList做降冪排列輸出

HashMap傳送門:http://goo.gl/P7771u
ArrayList傳送門:
                     
?
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Test {
    public static void main(String args[]){
        String s ="Jane Cobden (1851–1947) was a British Liberal politician "
                + "and radical activist. An early proponent of women rights, "
                + "she was one of two women elected to the inaugural London "
                + "County Council in 1889, although legal challenges prevented "
                + "her from being a councillor. Throughout her life she sought "
                + "to protect and develop the legacy of her father, the "
                + "Victorian reformer Richard Cobden, in particular the causes "
                + "of land reform, peace, social justice and women suffrage. "
                + "She was also a consistent advocate for Irish independence. "
                + "In the  she extended her interests to advancing the rights "
                + "of the indigenous populations within colonial territories. "
                + "She opposed the Boer War of 1899–1902, and after the "
                + "establishment of the Union of South Africa in 1910 she "
                + "attacked its segregationist policies. Before the First World"
                + " War she spoke out against Joseph Chamberlain tariff reform "
                + "crusade on the grounds of her father free trade principles, "
                + "and was prominent in the Liberal Party revival of the land "
                + "reform issue. In 1928 she presented the old Cobden family "
                + "residence, Dunford House, to the Cobden Memorial Association "
                + "as a centre dedicated to the issues and causes that had defined "
                + "\"Cobdenism”.";
        Pattern pattern = Pattern.compile("[a-zA-Z]+");
        Matcher matcher = pattern.matcher(s);
        /**宣告HashMap*/
        HashMap<string, integer=""> hashMap = new HashMap<string, integer="">();
         
        String sub;
        int count = 0;
        while (matcher.find()) {
            sub = s.substring(matcher.start(),matcher.end());
            if(hashMap.get(sub)==null){  //如果HashMap裡沒有這個單字
                hashMap.put(sub, 1);     //將此單字加入HashMap,數量為1
                count++;
            }  
            else
                hashMap.put(sub, hashMap.get(sub)+1);//如果有此單字,將數量+1
         
        }
        System.out.println("Total: "+count+" words.");
        /**利用ArrayList做HashMap Sort*/
        List<map.entry<string, integer="">> list = new ArrayList<map.entry<string,integer>>(hashMap.entrySet());
        Collections.sort(list,new Comparator<map.entry<string, integer="">>() {
            @Override
            public int compare(Map.Entry<string, integer=""> entry1, Map.Entry<string, integer=""> entry2) {
                return (entry2.getValue()-entry1.getValue());
            }
        });
        for (Map.Entry<string, integer=""> entry:list){
            System.out.print(entry.getKey()+" : "+hashMap.get(entry.getKey())+"\t");
        }
    }
}