1. 程式人生 > >正則表示式獲取

正則表示式獲取

package dkc_Parrtern1;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/*
     正則表示式的獲取
         配合IO流,從一個文字讀取檔案,獲取檔案裡面單詞的個數
 */
public class RegexDemo7 {
    public static void main(String[] args) {
        
//在E盤的word.txt中隨便寫入幾行漢字加單詞 /*大家好!hello everybody,我來自寒寨, My name is duxiansen,I come from HanZhai.哈哈*/ File file = new File("E:\\word.txt"); //1.讀取檔案宣告BufferedReader物件br BufferedReader br = null; //2.建立Pattern的物件,傳入一個正則表示式 Pattern p = null; //3.呼叫p物件中的matcher 獲取匹配器物件
Matcher matcher = null; //4.定義計算器 int count = 0; try { br = new BufferedReader(new FileReader(file)); String str =""; while((str = br.readLine()) != null) { p = Pattern.compile("\\b[a-zA-Z]+\\b"); matcher
= p.matcher(str); while(matcher.find()) { count++; } } System.out.println(count); br.close(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
package dkc_Parrtern1;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/*
     正則表示式的獲取功能:
     Pattern和Matcher類的使用
         jin tian yao xia yu,da jia pa bu pa?huang bu huang? are you sure?
         獲取由三個字元組成的單詞
 */
public class RegexDemo6 {
    public static void main(String[] args) {
        String str = "jin tian yao xia yu,da jia pa bu pa?huang bu huang? are you sure?";
        //1.建立Pattern的物件,傳入一個正則表示式
        Pattern p = Pattern.compile("\\b[a-zA-Z]{3}\\b");//(\\b單詞的邊界)
        
        //呼叫p物件中的matcher 獲取匹配器物件
        Matcher matcher = p.matcher(str);
        
        //遍歷得結果
        int count = 0;
        while(matcher.find()) {
            System.out.print(matcher.group()+" ");
            count++;
        }
        System.out.println(count);
        // 不能單獨使用,必須和found方法配合使用,否則報錯:No match found 
        //System.out.println(matcher.group());
    }
}