正則表達式

認識正則表達式

通過之前一些列的分析可以發現,String是一個非常萬能的類型,因爲String不僅僅可以支持各種字符串的處理操作,也支持有向各個數據類型的轉換功能,所以在項目的開發之中,只要是用戶輸入的信息基本上都用String表示。於是在向其他數據類型轉換的時候,爲了保證轉換的正確性,往往需要對其進行一些複雜的驗證處理,那麼這種情況下如果只是單純的依靠String的方法是非常麻煩的。
現在假設有一個字符串要求你判斷是否由數字所組成,如果由數字所組成則將其變爲數字進行乘法計算。

package cn.mldn.demo ;

public class DeadLock {
	public static void main(String[] args) throws Exception {
		String str = "123" ;
		if (isNumber(str)) {
			int num = Integer.parseInt(str) ;
			System.out.println(num * 2);
		}
	}
	public static boolean isNumber(String str) {
		char data [] = str.toCharArray();
		for (int x = 0; x < data.length ; x ++) {
			if (data[x] > '9' || data[x] < '0') {
				return false ;
			}
		}
		return true ;
}
}

實際上這種驗證的功能是非常簡單的,但是這如此簡單的功能卻需要開發者編寫大量的程序邏輯代碼,那麼如果是更加複雜的驗證呢?那麼在這樣的情況下,對於驗證來講最好的做法就是利用正則表達式來完成。
範例:使用正則表達式實現同樣的效果

package cn.mldn.demo ;

public class DeadLock {
	public static void main(String[] args) throws Exception {
		String str = "123" ;
		if (str.matches("\\d+")) {
			int num = Integer.parseInt(str) ;
			System.out.println(num * 2);
		}
	}
}

正則表達式最早是從Perl語言裏面發展而來的,而後在JDK1.4以前如果需要使用到正則表達式的相關定義則需要單獨引入其他的*.jar文件,但是從JDK1.4之後,正則已經默認被JDK所支持,並且提供有java.util.regex開發包,同時針對於String類也進行了一些修改,使其可以由方法直接支持正則處理。
使用正則最大的特點在於方便進行驗證處理,以及方便進行復雜字符串的修改處理。

常用正則標記(背)

如果要想進行正則的處理操作,那麼就首先需要對常用的正則標記有所掌握,從JDK1.4開始提供有java.util.regex開發包,這個包裏面提供有一個Pattern程序類,在這個程序類裏面定義有所支持的正則標記。
1、【數量:單個】字符匹配
任意字符:表示由任意字符組成;

package cn.mldn.demo ;

public class DeadLock {
	public static void main(String[] args) throws Exception {
		String str = "a" ;	// 要判斷的數據
		String regex = "a" ;	// 正則表達式
		System.out.println(str.matches(regex)) ;	// true
		}
	}

\: 匹配“\” ;
\n: 匹配換行 ;
\t: 匹配製表符 ;
2、【數量:單個】字符集(可以從裏面任選一個字符)
[ abc ] :表示可能是字母a、b、c中的任意一個;
[ ^abc ]:表示不是由字母a、b、c中的任意一個;

package cn.mldn.demo ;

public class DeadLock {
	public static void main(String[] args) throws Exception {
		String str = "x" ;	// 要判斷的數據
		String regex = "[^abc]" ;	// 正則表達式
		System.out.println(str.matches(regex)) ;	// true
		}
	}
package cn.mldn.demo ;

public class DeadLock {
	public static void main(String[] args) throws Exception {
		String str = "x" ;	// 要判斷的數據
		String regex = "[a-zA-Z]" ;	// 正則表達式
		System.out.println(str.matches(regex)) ;	// true
		}
	}
package cn.mldn.demo ;

public class DeadLock {
	public static void main(String[] args) throws Exception {
		String str = "1" ;	// 要判斷的數據
		String regex = "[0-9]" ;	// 正則表達式
		System.out.println(str.matches(regex)) ;	// true
		}
	}

3、【數量:單個】簡化字符集
“ . ”:表示任意的一個字符;

package cn.mldn.demo ;

public class DeadLock {
	public static void main(String[] args) throws Exception {
		String str = "#" ;	// 要判斷的數據
		String regex = "." ;	// 正則表達式
		System.out.println(str.matches(regex)) ;	// true
		}
	}

\d : 等價於“0-9”範圍;

package cn.mldn.demo ;

public class DeadLock {
	public static void main(String[] args) throws Exception {
		String str = "1" ;	// 要判斷的數據
		String regex = "\\d" ;	// 正則表達式
		System.out.println(str.matches(regex)) ;	// true
		}
	}

\D: 等價於[^0-9],不是一個數字;

package cn.mldn.demo ;

public class DeadLock {
	public static void main(String[] args) throws Exception {
		String str = "a" ;	// 要判斷的數據
		String regex = "\\D" ;	// 正則表達式
		System.out.println(str.matches(regex)) ;	// true
		}
	}

\s:匹配任意的一位空格、可能是空格、換行、製表符;

package cn.mldn.demo ;

public class DeadLock {
	public static void main(String[] args) throws Exception {
		String str = "a\t" ;	// 要判斷的數據
		String regex = "\\D\\s" ;	// 正則表達式
		System.out.println(str.matches(regex)) ;	// true
		}
	}

\S:匹配任意的非空格數據;
\w:匹配字母、數字、下劃線,等價於“[ a-zA-Z 0-9]” ;
\W:匹配非字母、數字、下劃線,等價於“[^a-zA-Z 0-9]”
4、邊界匹配:
^:匹配邊界開始;
$:匹配邊界結束;
5、數量表示,默認情況下只有添加上了數量單位纔可以匹配多位字符;
表達式?:該正則可以出現0次或1次;
表達式*:該正則可以出現0次、1次或多次;
表達式+:該正則可以出現1次或多次

package cn.mldn.demo ;

public class DeadLock {
	public static void main(String[] args) throws Exception {
		String str = "" ;	// 要判斷的數據
		String regex = "\\w*" ;	// 正則表達式
		System.out.println(str.matches(regex)) ;	// true
		}
	}

表達式{n}:表達式的長度正好爲n次;
表達式{n,}:表達式的長度爲n次以上;
表達式{n,m}:表達式的長度在n~m次;

package cn.mldn.demo ;

public class DeadLock {
	public static void main(String[] args) throws Exception {
		String str = "abc" ;	// 要判斷的數據
		String regex = "\\w*{3}" ;	// 正則表達式
		System.out.println(str.matches(regex)) ;	// true
		}
	}

6、邏輯表達式:可以連接多個正則:
表達式X表達式Y:X表達式之後緊跟上Y表達式;
表達式X|表達式Y:有一個表達式滿足即可;
(表達式):爲表達式設置一個整體描述,可以爲整體描述設置數量單位。

String類對正則的支持

在進行正則表達式大部分處理的情況下都會基於String類完成,並且在String類裏面提供有如下關於正則表達式的方法。
在這裏插入圖片描述
範例:實現字符串的替換(刪除掉非字母與數字)

package cn.mldn.demo ;

public class DeadLock {
	public static void main(String[] args) throws Exception {
		String str = "JJOR#$^FFRFB%23455f" ;	// 要判斷的數據
		String regex = "[^0-9a-zA-Z]+" ;	// 正則表達式
		System.out.println(str.replaceAll(regex, "")) ;
		}
	}

在這裏插入圖片描述
範例:實現字符串拆分

package cn.mldn.demo ;

public class DeadLock {
	public static void main(String[] args) throws Exception {
		String str = "a1b22c333d4444f55555g6666666" ;	// 要判斷的數據
		String regex = "\\d+" ;	// 正則表達式
		String result [] = str.split(regex) ;
		for (int x = 0; x < result.length ; x ++) {
			System.out.print(result[x] + "、");
		}
		}
	}

在這裏插入圖片描述
在正則處理的時候對於拆分與替換操作相對容易一些,但是比較麻煩的是數據驗證部分。
範例:判斷一個數據是否爲小數,如果是小數則將其變爲double類型

package cn.mldn.demo ;

public class DeadLock {
	public static void main(String[] args) throws Exception {
		String str = "100.1" ;	// 要判斷的數據
		String regex = "\\d+(\\.\\d+)?" ;	// 正則表達式
		System.out.println(str.matches(regex));	// true
		}
	}

範例:現在判斷一個字符串是否由日期所組成,如果是由日期所組成則將其轉爲Date類型

package cn.mldn.demo ;

import java.text.SimpleDateFormat ;

public class DeadLock {
	public static void main(String[] args) throws Exception {
		String str = "1998-10-15" ;	// 要判斷的數據
		String regex = "\\d{4}-\\d{2}-\\d{2}" ;	// 正則表達式
		if (str.matches(regex)) {
			System.out.println(new SimpleDateFormat("yyyy-MM-dd").parse(str)) ;
		}
		
		}
	}

在這裏插入圖片描述
需要注意的是,正則表達式無法對立面的內容進行判斷,只能夠對格式進行判斷處理。
範例:判斷給定的電話號碼是否正確?
電話號碼:51283346; \d{7,8}
電話號碼:01051283346
電話號碼:(010)-51283345。

package cn.mldn.demo ;

import java.text.SimpleDateFormat ;

public class DeadLock {
	public static void main(String[] args) throws Exception {
		String str = "51283346" ;	// 要判斷的數據
		String regex = "\\d{7,8}" ;	// 正則表達式
		System.out.println(str.matches(regex));	// true
		
		}
	}
package cn.mldn.demo ;

import java.text.SimpleDateFormat ;

public class DeadLock {
	public static void main(String[] args) throws Exception {
		String str = "01051283346" ;	// 要判斷的數據
		String regex = "(\\d{3,4})?\\d{7,8}" ;	// 正則表達式
		System.out.println(str.matches(regex));	// true
		
		}
	}
package cn.mldn.demo ;

import java.text.SimpleDateFormat ;

public class DeadLock {
	public static void main(String[] args) throws Exception {
		String str = "(010)-51283346" ;	// 要判斷的數據
		String regex = "((\\d{3,4})|(\\(\\d{3,4}\\)-))?\\d{7,8}" ;	// 正則表達式
		System.out.println(str.matches(regex));	// true
		
		}
	}

既然已經可以使用正則進行驗證了,那麼下面就可以利用其來實現一個email地址格式的驗證。
範例:驗證email格式
email的用戶可以由字母、數字、所組成;(不應該使用“”開頭);
email的域名可以由字母、數字、_、-所組成;
域名的後綴必須是:.cn、.com、,net、.com.cn、.gov;
在這裏插入圖片描述

package cn.mldn.demo ;

public class DeadLock {
	public static void main(String[] args) throws Exception {
		String str = "[email protected]" ;	// 要判斷的數據
		String regex = "[a-zA-Z0-9]\\w+@\\w+\\.(cn|com|com.cn|net|gov)" ;	// 正則表達式
		System.out.println(str.matches(regex));	// true
		
		}
	}

現在這幾種正則的匹配操作是最常用的幾種方式。

java.util.regex包支持

雖然在大部分的情況下都可以利用String類實現正則的操作,但是也有一些情況下需要使用到java.util.regex開發包中提供的正則處理類,在這個包裏面一共定義有兩個類:Pattern(正則表達式編譯)、Matcher(匹配)。
1、Pattern類提供有正則表達式的編譯處理支持:public static Pattern compile(String regex)
同時也提供有字符串的拆分操作:public String[] split(CharSequence input);

package cn.mldn.demo ;

import java.util.regex.Pattern;

public class DeadLock {
	public static void main(String[] args) throws Exception {
		String str = "JKL()UI^&()JKLSD()QW@#$WEFEF" ;	// 要判斷的數據
		String regex = "[^a-zA-Z]+" ;	// 正則表達式
		Pattern pat = Pattern.compile(regex) ;	// 編譯正則表達式
		String result [] = pat.split(str) ;	// 拆分
		for (int x = 0; x < result.length ; x ++) {
			System.out.println(result[x]);
		}	
	}
}

2、Matcher類,實現了正則匹配的處理類,這個類的對象實例化依靠Pattern類完成:
Pattern類提供的方法:public Matcher matcher(CharSequence input);
當獲取了Matcher類的對象之後就可以利用該類中的方法進行如下操作:
正則匹配:public boolean matches();
字符串替換:public String replaceAll(String replacement)

package cn.mldn.demo ;

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

public class DeadLock {
	public static void main(String[] args) throws Exception {
		String str = "101" ;	// 要判斷的數據
		String regex = "\\d+" ;	// 正則表達式
		Pattern pat = Pattern.compile(regex) ;	// 編譯正則表達式
		Matcher mat = pat.matcher(str) ;
		System.out.println(mat.matches());
	}
}

範例:字符串替換

package cn.mldn.demo ;

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

public class DeadLock {
	public static void main(String[] args) throws Exception {
		String str = "1KKK3KK3NGKF344KKDF34 &*(f F" ;	// 要判斷的數據
		String regex = "\\D+" ;	// 正則表達式
		Pattern pat = Pattern.compile(regex) ;	// 編譯正則表達式
		Matcher mat = pat.matcher(str) ;
		System.out.println(mat.replaceAll(""));
	}
}

在這裏插入圖片描述
如果純粹的是以拆分、替換、匹配三種操作爲例根本用不到java.util.regex開發包,只依靠String類就都可以實現了。但是Matcher類裏面提供有一種分組的功能,而這種分組的功能是String不具備的。

package cn.mldn.demo ;

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

public class DeadLock {
	public static void main(String[] args) throws Exception {
		// 要求取出“#{內容}標記中的所有內容”
		String str = "INSERT INTO dept(deptno,dname,loc) VALUES (#{deptno}, #{dname}, #{loc})" ;	// 要判斷的數據
		String regex = "#\\{\\w+\\}" ;	// 正則表達式
		Pattern pat = Pattern.compile(regex) ;	// 編譯正則表達式
		Matcher mat = pat.matcher(str) ;
		while(mat.find()) {	// 是否有匹配成功的內容
			System.out.println(mat.group(0).replaceAll("#|\\{|\\}", ""));
		}
		
	}
}

java.util.regex開發包,如果不是進行一些更爲複雜的正則處理是很難使用到的,而String類所提供的只適合用於正則的基本操作。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章