Java 程式設計 -- 正規表達式 (Regex)
Java 程式簡介運算式分枝迴圈陣列函數遞迴錯誤處理物件導向封裝繼承多型技巧函式庫字串數學正規表達式容器檔案網路資料庫視窗ThreadListener錯誤陷阱相關檔案相關資源教學錄影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())); } } } |
page revision: 0, last edited: 04 Nov 2010 03:50
Post preview:
Close preview