Java學習系列(二十四)JavaRegex詳解

來源:互聯網
上載者:User

標籤:Regex   郵箱   正則   regex   java   


轉載請註明出處:http://blog.csdn.net/lhy_ycu/article/details/45501777

前言

Regex可以說是用來處理字串的一把利器,它是一個專門匹配n個字串的字串模板,本質是尋找和替換。在執行個體示範之前先瞭解一下Pattern、Matcher這兩個工具類,Pattern:編譯好的帶匹配的模板(如:Pattern.compile("[a-z]{2}");/ / 取2個小寫字母);Matcher:匹配目標字串後產生的結果(如:pattern.matcher("目標字串");)。字串還有一個內建的matches方法用來判斷目標字串是否匹配給定的Regex,格式為:targetStr.matches(regex); 傳回型別為boolean。


基本使用方式
 (一)支援的基本萬用字元:

.   -可以匹配任一字元
\s  -代表一個任意空白(空格、Tab)。
\S  -代表一個任意的非空白。
\d  -代表一個任意的數字(digital)。
\D  -代表一個任意的非數字。
\w  -代表一個單詞字元。
-W  -代表一個任意的非單詞字元

注意:對於特殊字元,實際使用時記住要轉義\ ,如:( ) [ ] { } \ ? * + ^(一行的開頭) $(一行的結尾)|

(二)取值範圍(用作出現次數的“副詞”)

? --代表它前面的東西可以出現0~1次
* --代表它前面的東西可以出現0~N次
+ --代表它前面的東西可以出現1~N次
{n,m} --代表它前面的東西可以出現n~m次
{n,} --代表它前面的東西至少出現n次
{,m} --代表它前面的東西最多出現m次
{n} --代表它前面的東西必須出現n次

(三)方括號運算式

枚舉:[ab1]  --代表a或b或者1。
範圍:[a-c]  --代表a,b,c中的任意一個字元。
枚舉與範圍:[a-c1-3]--代表a,b,c,1,2,3中的任意一個字元。
表示求否:[^a-c] --代表不含a,b,c其中任意一個字元。
表示求交:[a-g&&[^b-d]]:--代表a,e,f,g中的任意一個字元。
表示必須含有其中之一:(com|org|cn)

總結:一個字元用\,多個字元用[],字元次數用{} 


執行個體說明

(一)基本用法示範:

/** * Regex執行個體示範說明 *  * @author [*昨日重現*] [email protected] * @since version 1.0 * @datetime 2015年5月5日 下午2:27:50 */public class RegexTest {public static void main(String[] args) {// 單個字元System.out.println("a".matches("."));// 0~1個aSystem.out.println("a".matches("a?"));// 1~N個aSystem.out.println("aaaa".matches("a+"));// 0~N個aSystem.out.println("".matches("a*"));// 1~N個q和1個0~9之間的數字System.out.println("qqqqqq3".matches("q+[0-9]"));// 12~100個數字System.out.println("12345667890123".matches("\\d{12,100}"));// 0~3個數字分別以.分割System.out.println("192.168.0.1".matches("\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}"));// 第一個數字0~2,第二個數字0~9,第三個數字0~9System.out.println("192".matches("[0-2][0-9][0-9]"));// 4個任意空白System.out.println(" \n\r\t".matches("\\s{4}"));// 特殊字元\需轉義System.out.println("\\".matches("\\\\"));// 以h開頭,中間有0~N個字元,最後以o結尾System.out.println("hello".matches("^.*o$"));// 以h開頭,中間1~3個字母尾隨一個o,接著空白連著0~N個字元並以d結尾System.out.println("hello world".matches("^h[a-z]{1,3}o\\b.*d$"));// 以任意空白且不以換行開頭為開頭,並以換行結尾System.out.println("   \n".matches("^[\\s&&[^\\n]]*\\n$"));// 0~N個字元,串連4個數字和一個字元System.out.println("aaa 2222q".matches(".*\\d{4}."));}}

(二)實際應用示範:

1、讀取網頁中所有的郵箱地址

/** * 讀取某個網頁中的所有郵箱地址--基本尋找 *  * @author [*昨日重現*] [email protected] * @since version 1.0 * @datetime 2015年5月5日 下午4:20:00 */public class EmailTest {public static void main(String[] args) {// 1~N個單詞(可能含有.、-)串連 @1~N個單詞連著 . 最後以com|org|cn|net其中之一結尾String emailTemplate = "[\\w[.-]][email protected][\\w]+\\.(com|org|cn|net)";BufferedReader br = null;try {br = new BufferedReader(new InputStreamReader(new FileInputStream("d:\\email.html")));String line = null;StringBuffer sb = new StringBuffer();while ((line = br.readLine()) != null) {sb.append(line).append("\n");}parse(sb.toString(), emailTemplate);} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} finally {try {br.close();} catch (Exception e2) {// TODO: handle exceptione2.printStackTrace();}}}/** * 列印網頁中的所有郵箱地址 *  * @param targetStr *            目標字串 * @param template *            待編譯的正則模板 */public static void parse(String targetStr, String template) {if (targetStr == null || template == null) {return;}// 擷取編譯好的待匹配的模板Pattern pattern = Pattern.compile(template);// 擷取匹配目標字串後產生的結果Matcher matcher = pattern.matcher(targetStr);// 若尋找下一個匹配Regex的字串while (matcher.find()) {// 則取出上一次與Regex匹配的字串。System.out.println("=======" + matcher.group());}}}

2、程式碼數統計:

/** * 代碼統計:遍曆某個項目的源檔案的程式碼數。 *  * 包括:空白行數、程式碼數、注釋行數。 *  * @author [*昨日重現*] [email protected] * @since version 1.0 * @datetime 2015年5月5日 下午4:40:12 */public class CodeCounter {/** * 空白行數 */private static long whiteLines = 0;/** * 程式碼數 */private static long normalLines = 0;/** * 注釋行數 */private static long commentLines = 0;public static void main(String[] args) { File srcDir = new File("D:\\workspace\\android\\Abc\\src");myList(srcDir);// 遍曆所java源檔案System.out.println("whiteLines = " + whiteLines);System.out.println("normalLines = " + normalLines);System.out.println("commentLines = " + commentLines);System.out.println("totalLines = " + getTotalLines());}/** * 擷取總行數 */private static long getTotalLines() {long value = whiteLines + normalLines + commentLines;return value;}/** * 遍曆所java源檔案 */private static void myList(File srcDir) {System.out.println(srcDir + "目錄下包含的目錄和子檔案有:");File[] files = srcDir.listFiles();for (File file : files) {System.out.println("----------" + file);if (file.getName().matches(".*\\.java$")) {parse(file);}if (file.isDirectory()) {myList(file);}}}/** * 讀取源檔案內容 *  * @param file *            java檔案 */private static void parse(File file) {BufferedReader br = null;/** * 標識注釋的開始或結束 */boolean comment = false;try {br = new BufferedReader(new InputStreamReader(new FileInputStream(file)));String line = null;while ((line = br.readLine()) != null) {line = line.trim();// 以任意空白且不以換行開頭為開頭,並以換行結尾if (line.matches("^[\\s&&[^\\n]]*$")) {whiteLines++;} else if (line.startsWith("/*")) {commentLines++;comment = true;} else if (comment == true) {commentLines++;if (line.endsWith("*/")) {comment = false;}} else if (line.contains("//")) {commentLines++;} else {normalLines++;}}} catch (IOException e) {e.printStackTrace();} finally {if (br != null) {try {br.close();br = null;} catch (IOException e) {e.printStackTrace();}}}}}

(三)Regex進階使用:

尋找子串

String s1 = "123-45678-987-11";Pattern pattern = Pattern.compile("\\d{3,5}"); // 匹配3~5個數字Matcher matcher = pattern.matcher(s1);System.out.println(matcher.matches());// falsematcher.reset();// 重設匹配器,將其添加位置設定為零System.out.println(matcher.find());// true,由於重設了匹配器此時將從起始位置尋找System.out.println(matcher.start() + "-" + matcher.end());// 位置:0-3// 與matches方法唯一不同的是lookingAt不需要匹配整個地區 ,它永遠是從第一個子串開始System.out.println(matcher.lookingAt());// trueSystem.out.println(matcher.lookingAt());// true

尋找與替換

// CASE_INSENSITIVE:忽略子串大小寫Pattern pattern2 = Pattern.compile("java", Pattern.CASE_INSENSITIVE);Matcher matcher2 = pattern2.matcher("java Java JAVA jaVA jAVA ILoveYouJaVA youhateJaVa");// 將尋找到的所有子串進行替換 (尋找並替換)System.out.println(matcher2.replaceAll("JAVA"));

結束語
關於Java中Regex的基本使用差不多就這些了,當然Regex的作用遠不止這些,至於更深層次的應用以後遇到了會更新上去。截止目前,JavaSE基礎差不多到這裡了,後面會更新Java效能最佳化、深入理解JVM、Android學習系列等,敬請期待!


Java學習系列(二十四)JavaRegex詳解

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.