Java 程式設計 -- 正規表達式 (Regex)

Java 程式

簡介

運算式

分枝

迴圈

陣列

函數

遞迴

錯誤處理

物件導向

封裝

繼承

多型

技巧

函式庫

字串

數學

正規表達式

容器

檔案

網路

資料庫

視窗

Thread

Listener

錯誤陷阱

相關檔案

相關資源

教學錄影

Eclipse

考題解答

訊息

相關網站

參考文獻

最新修改

簡體版

English

範例一:正規表達式

import java.util.regex.*;
 
public class Regex1 {
    public static void main(String args[]) {
// Match Alphabet 
        System.out.println("====== Match Alphabet ==========");
        String pattern = "[\\w]+";
        String text = "Dear Snoopy, How are you !.";
        Pattern p = Pattern.compile(pattern);
        Matcher m = p.matcher(text);
        while (m.find()) {
            System.out.println("token="+text.substring(m.start(), m.end()));
        }
// Match Alphabet 
        System.out.println("====== Match Alphabet ==========");
        pattern = "[a-zA-Z]+";
        text = "Dear Snoopy, How are you !.";
        p = Pattern.compile(pattern);
        m = p.matcher(text);
        while (m.find()) {
            System.out.println("token="+text.substring(m.start(), m.end()));
        }
 
// Create a pattern to match breaks
        System.out.println("====== Split by , and space ==========");
        p = Pattern.compile("[,\\s]+");
        String[] results = p.split("one,two, three   four ,  five");
        for (int i=0; i<results.length; i++)
            System.out.println(results[i]);
 
// Create a pattern to match cat
        System.out.println("====== replace cat by dog ==========");
        p = Pattern.compile("cat");
        m = p.matcher("one cat, two cats in the yard");
        StringBuffer sb = new StringBuffer();
        boolean result = m.find();
        while(result) {
            m.appendReplacement(sb, "dog");
            result = m.find();
        }
        m.appendTail(sb);
        System.out.println(sb.toString());
 
// Match URL 
        System.out.println("====== Match URL ==========");
        pattern = "http://[\\w/\\.]{5,100}";
        text = "URL of KMIT is http://www.kmit.edu.tw/, URL of ccc is http://ccc.kmit.edu.tw/";
        p = Pattern.compile(pattern);
        m = p.matcher(text);
        while (m.find()) {
            System.out.println("token="+text.substring(m.start(), m.end()));
        }
    }
}

Facebook

Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-NonCommercial-ShareAlike 3.0 License