黑馬程序員_正則表達式

  ------- android培訓java培訓、期待與您交流! ----------


一    正則表達式
1 正則表達式是符合一定規則的表達

2 作用:專門用於操作字符串

3 好處:可以簡化對字符串的操作

4 弊處:定義越多,閱讀性差
4 特點:用一些特定的符號表示代碼操作,可以簡化書寫

5 摘要:
(1)字符類 :
[abc]:只能 a、b 或 c 
[^abc]:任何字符,除了 a、b 或 c 
[a-zA-Z]:表示a 到 z 或 A 到 Z 

(2)預定義字符類 
.:表示任何字符 
\d:數字[0-9] 
\D:非數字  [^0-9] 
\w:單詞字符  [a-zA-Z_0-9] 
\W:非單詞字符  [^\w] 

(3)數量詞 
X?:X,一次或一次也沒有 
X*:X,零次或多次 
X+:X,一次或多次 
X{n}:X,恰好 n 次 
X{n,}:X,至少 n 次 
X{n,m}:X,至少 n 次,但是不超過 m 次 

6 關於正則表達式的方法
(1)String類中的matches(String regex);//匹配,返回boolean型

例子:

class MatchesDemo 
{
	public static void main(String[] args) 
	{
		//校驗qq號
		String qq="22a2222";
		//定義個規則,第一位是0-9,第二位0-9,總共是5-15位
		String regex1="[1-9]\\d{4,14}";
		//匹配qq號
		boolean b1=qq.matches(regex1);
		System.out.println(b1);

		//校驗手機號
		String tel="1582a347544";
		//定義規則,第一位只能是1,第二位可以是358,必須是11位
		String regex2="1[358]\\d{9}";
		//匹配手機號
		boolean b2=tel.matches(regex2);
		System.out.println(b2);
	}
}


(2)String類中的split(String regex);//切割,返回字符串數組

例子:

class  SplitDemo
{
	public static void main(String[] args) 
	{
		String s1="a..b...c.";
		//規則:按.切,但是.是特殊字符,所以要轉義
		String regex1="\\.+";
		String[] str1=s1.split(regex1);
		for(String str:str1)
		{
			System.out.println(str);
		}

		System.out.println("------------------------");

		String s2="ddaffbttc";
		//規則:按疊詞切,需要用到組(.)\\1
		String regex2="(.)\\1";
		String[] str2=s2.split(regex2);
		for(String str:str2)
		{
			System.out.println(str);
		}
	}
}

(3)String類中的replaceAll(String regex,String newstr);//替換,將符合規則的字符串替換成指定的字符串,返回一個字符串
例子:

class  ReplaceAllDemo
{
	public static void main(String[] args) 
	{
		String s1="ffffasssbjjjjcdddddd";
		//規則:疊詞
		String regex1="(.)\\1+";
		//將疊詞替換成單個#
		String s2=s1.replaceAll(regex1,"#");
		System.out.println(s2);
		//將疊詞替換成單個單詞
		String s3=s1.replaceAll(regex2,"$1");
		//注意:美元符號的意思是拿前面規則的第一個組
		System.out.println(s3);
	}
}

(4)獲取:獲取字符串中符合規則的字符串
1 將正則表達式封裝成對象,Pattern類
2 將字符串與正則表達式對象相關聯
3 關聯後獲取正則匹配器,Matcher類
4 通過匹配對符合規則的子串進行操作
例子:

import java.util.regex.*;
class GetDemo 
{
	public static void main(String[] args) 
	{
		String str="aaa bbbb ccc dddd eee ffff";
		//定義規則
		String regex="\\b[a-z]{3}\\b";
		//將規則封裝成對象
		Pattern p=Pattern.compile(regex);
		//讓字符串與正則對象相關聯,並獲取匹配器
		Matcher m=p.matcher(str);
		//獲取符規則的子串
		while(m.find())//查找
		{
			//獲取子串
			System.out.println(m.group());
			//獲取子串的開始位和結束位
			System.out.println(m.start()+"::"+m.end());
		}
	}
}

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