1. 程式人生 > >Java之Pattern和Matcher的作用

Java之Pattern和Matcher的作用

java.util.regex.Pattern類的例項的主要作用是給正則表示式一個匹配模式,因為在java裡面正則表示式是一個字串,字串的能力是非常有限的,不像javascriptnaya那樣可以在正則表示式末尾新增"g" "i" "m"來指定全域性匹配、區分大小寫匹配和多行匹配(如"/\b\w/gi")。因此在java裡面需要Pattern例項來包裝正則表示式zifu字串,然後通過Pattern例項的方法來設定·匹配模式。

java.util.regex.Matcher類的例項的作用是增加表示式匹配字串的權利,讓正則表示式更自由的匹配字串。比如呼叫Matcher例項的方法,正則表示式可以匹配整個字串、可以匹配字串最前端的子串、最後段的子串、或者任意位置的子串等等。 

Pattern的用法

  • Pattern complie(String regex)

       由於Pattern的建構函式是私有的,不可以直接建立,所以通過靜態方法compile(String regex)方法來建立,將給定的正則表示式編譯並賦予給Pattern類。

  • String pattern()

        返回正則表示式的字串形式,其實就是返回Pattern.complile(String regex)的regex引數

String regex = "\\?{2}";
Pattern pattern = Pattern.compile(regex);
String str = pattern.pattern();
System.out.println(str);// \?{2}
  • Pattern compile(String regex, int flags)

       方法功能和compile(String regex)相同,不過增加了flag引數

  • int flags()

       返回當前Pattern的匹配flags引數。flag引數用來控制正則表示式的匹配行為,可取值範圍如下:

Pattern.CANON_EQ 當且僅當兩個字元的”正規分解(canonical decomposition)”都完全相同的情況下,才認定匹配.比如用了這個標誌之後,表示式”a\u030A”會匹配”?”.預設情況下,不考慮”規範相等性(canonical equivalence)”.

Pattern.CASE_INSENSITIVE(?i) 預設情況下,大小寫不明感的匹配只適用於US-ASCII字符集.這個標誌能讓表示式忽略大小寫進行匹配.要想對Unicode字元進行大小不明感的匹 配,只要將UNICODE_CASE與這個標誌合起來就行了.

Pattern.COMMENTS(?x) 在這種模式下,匹配時會忽略(正則表示式裡的)空格字元(譯者注:不是指表示式裡的”\s”,而是指表示式裡的空格,tab,回車之類).註釋從#開始,一直到這行結束.可以通過嵌入式的標誌來啟用Unix行模式.

Pattern.DOTALL(?s)在這種模式下,表示式’.’可以匹配任意字元,包括表示一行的結束符。預設情況下,表示式’.’不匹配行的結束符.

Pattern.MULTILINE(?m)在這種模式下,’\^’和’$’分別匹配一行的開始和結束.此外,’^’仍然匹配字串的開始,’$’也匹配字串的結束.預設情況下,這兩個表示式僅僅匹配字串的開始和結束.

Pattern.UNICODE_CASE(?u) 在這個模式下,如果你還啟用了CASE_INSENSITIVE標誌,那麼它會對Unicode字元進行大小寫不明感的匹配.預設情況下,大小寫不敏感的匹配只適用於US-ASCII字符集.

Pattern.UNIX_LINES(?d) 在這個模式下,只有’\n’才被認作一行的中止,並且與’.’,’^’,以及’$’進行匹配.

Pattern pattern = Pattern.compile("\\?{2}",Pattern.CASE_INSENSITIVE);
int i = pattern.flags();
//Pattern原始碼對CASE_INSENSITIVE常量定義為:
//public static final int CASE_INSENSITIVE = 0x02;
System.out.println(i);// 2
  • Pattern.matcher(CharSequence input)

       對指定輸入的字串建立一個Matcher物件。Matcher物件一般通過這個方法生成。CharSequence是個interface,String類實現了CharSequence介面,因此可以傳入String型別的值。

Pattern pattern = Pattern.compile("\\?{2}");
Matcher matcher = pattern.matcher("??");
//matcher的matches方法是對字串整合匹配。只有整個字串符合正則表示式才會返回true
boolean matches = matcher.matches();// true
  • String[] split(CharSequence input) 根據正則表示式分割傳入的這個字串。

  • String[] split(CharSequence input, int limit) 功能和String[] split(CharSequence input)相同,增加引數limit目的在於要指定分割的段數

Pattern pattern = Pattern.compile("[#_-]");
String str = "lao#lian_shi_shui-?";
String[] arrays = pattern.split(str, 3);
for (String s : arrays) {
	System.out.println(s);
}

/*控制檯輸出為:
lao
lian
shi_shui-?

也就是arrays陣列存放著3個元素。從這裡可以看出,Pattern的split方法類似於String的split方法。
*/

還有其他的方法請參考其他的文章。

Matcher類的使用

  • boolean matches()

最常用方法:嘗試對整個目標字元展開匹配檢測,也就是隻有整個目標字串完全匹配時才返回真值.

Pattern pattern = Pattern.compile("\\?{2}");
Matcher matcher = pattern.matcher("??");
boolean matches = matcher.matches();//true
System.out.println(matches);
matcher=pattern.matcher("?");
matches = matcher.matches();//false
System.out.println(matches);
  • boolean lookingAt()

對前面的字串進行匹配,只有匹配到的字串在最前面才會返回true

Pattern p = Pattern.compile("\\d+");
Matcher m = p.matcher("22bb23");
boolean match = m.lookingAt();//true
System.out.println(match);
m = p.matcher("bb2233");
match= m.lookingAt();
System.out.println(match);//false
  • boolean find()

對字串進行匹配,匹配到的字串可以在任何位置

Pattern p = Pattern.compile("\\d+");
Matcher m = p.matcher("22bb23");
m.find();// 返回true
Matcher m2 = p.matcher("aa2223");
m2.find();// 返回true
Matcher m3 = p.matcher("aa2223bb");
m3.find();// 返回true
Matcher m4 = p.matcher("aabb");
m4.find();// 返回false
  • int start()

返回當前匹配到的字串在原目標字串中的位置

  • int end()

返回當前匹配的字串的最後一個字元在原目標字串中的索引位置.

  • String group()

返回匹配到的子字串

Pattern p = Pattern.compile("\\d+");
Matcher m = p.matcher("aa22bb23");
m.find();
int start = m.start();//2
String group = m.group();//22
int end = m.end();//4
System.out.println(start);
System.out.println(group);
System.out.println(end);

還有其他方法請參考其他文章。

Pattern和Matcher使用完整例子

    public static void main(String[] args) {
		String str = "abcdefg";
		String regex = "ABC*";
		// 匹配時忽略大小寫
		Pattern pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
		// 包裝被匹配的字串
		Matcher matcher = pattern.matcher(str);
		// 看看被匹配的字串是否有正則表示式描述的子串
		boolean bool = matcher.find();
		System.out.println(bool);// true
	}