28 正則表示式的應用

1。 正則表示式的應用

String 類提供的幾個特殊方法

1。1 匹配功能

public boolean matches(String regex) // 編譯給定正則表示式並嘗試將給定輸入與其匹配。

校驗郵箱

package cn。itcast_02;

import java。util。Scanner;

/*

* 校驗郵箱

*

* 分析:

* A:鍵盤錄入郵箱

* B:定義郵箱的規則

* 1517806580@qq。com

* liuyi@163。com

* linqingxia@126。com

* fengqingyang@sina。com。cn

* fqy@itcast。cn

* C:呼叫功能,判斷即可

* D:輸出結果

*/

public class RegexTest {

public static void main(String[] args) {

//鍵盤錄入郵箱

Scanner sc = new Scanner(System。in);

System。out。println(“請輸入郵箱:”);

String email = sc。nextLine();

//定義郵箱的規則

//String regex = “[a-zA-Z_0-9]+@[a-zA-Z_0-9]{2,6}(\\。[a-zA-Z_0-9]{2,3})+”;

String regex = “\\w+@\\w{2,6}(\\。\\w{2,3})+”;

//呼叫功能,判斷即可

boolean flag = email。matches(regex);

//輸出結果

System。out。println(“flag:”+flag);

}

}1。2 分割功能

public String[] split(String regex) // 根據指定的正則表示式分割字串

程式碼示例:我有如下一個字串:”91 27 46 38 50”,請寫程式碼實現最終輸出結果是:”27 38 46 50 91”

package cn。itcast_03;

import java。util。Arrays;

/*

* 我有如下一個字串:“91 27 46 38 50”

* 請寫程式碼實現最終輸出結果是:“27 38 46 50 91”

*

* 分析:

* A:定義一個字串

* B:把字串進行分割,得到一個字串陣列

* C:把字串陣列變換成int陣列

* D:對int陣列排序

* E:把排序後的int陣列在組裝成一個字串

* F:輸出字串

*/

public class RegexTest {

public static void main(String[] args) {

// 定義一個字串

String s = “91 27 46 38 50”;

// 把字串進行分割,得到一個字串陣列

String[] strArray = s。split(“ ”);

// 把字串陣列變換成int陣列

int[] arr = new int[strArray。length];

for (int x = 0; x < arr。length; x++) {

arr[x] = Integer。parseInt(strArray[x]);

}

// 對int陣列排序

Arrays。sort(arr);

// 把排序後的int陣列在組裝成一個字串

StringBuilder sb = new StringBuilder();

for (int x = 0; x < arr。length; x++) {

sb。append(arr[x])。append(“ ”);

}

//轉化為字串

String result = sb。toString()。trim();

//輸出字串

System。out。println(“result:”+result);

}

}1。3 替換功能

public String replaceAll(String regex,String replacement)

使用給定的 replacement 替換此字串所有匹配給定的正則表示式的子字串。

論壇中不能出現數字字元,用*替換

package cn。itcast_04;

/*

* 替換功能

* String類的public String replaceAll(String regex,String replacement)

* 使用給定的 replacement 替換此字串所有匹配給定的正則表示式的子字串。

*/

public class RegexDemo {

public static void main(String[] args) {

// 定義一個字串

String s = “helloqq12345worldkh622112345678java”;

// 我要去除所有的數字,用*給替換掉

// String regex = “\\d+”;

// String regex = “\\d”;

//String ss = “*”;

// 直接把數字幹掉

String regex = “\\d+”;

String ss = “”;

String result = s。replaceAll(regex, ss);

System。out。println(result);

}

}1。4 獲取功能

Pattern和Matcher類的使用

package cn。itcast_05;

import java。util。regex。Matcher;

import java。util。regex。Pattern;

/*

* 獲取功能

* Pattern和Matcher類的使用

*

* 模式和匹配器的基本使用順序

*/

public class RegexDemo {

public static void main(String[] args) {

// 模式和匹配器的典型呼叫順序

// 把正則表示式編譯成模式物件

Pattern p = Pattern。compile(“a*b”);

// 透過模式物件得到匹配器物件,這個時候需要的是被匹配的字串

Matcher m = p。matcher(“aaaaab”);

// 呼叫匹配器物件的功能

boolean b = m。matches();

System。out。println(b);

//這個是判斷功能,但是如果做判斷,這樣做就有點麻煩了,我們直接用字串的方法做

String s = “aaaaab”;

String regex = “a*b”;

boolean bb = s。matches(regex);

System。out。println(bb);

}

}1。5 Pattern 匹配模式

Pattern類為正則表示式的編譯表示形式。指定為字串的表示式必須首先被編譯為此類的例項。然後,可將得到的模式用於建立Matcher物件,依照正則表示式,該物件可與任意字元序列匹配。執行匹配所涉及的所有狀態都駐留在匹配器中,所以多個匹配器可以共享同一個模式。

1。6 Matcher 匹配器

注意事項

Pattern類為正則表示式的編譯表示形式。指定為字串的正則表示式必須首先被編譯為此類的例項。然後,可將得到的模式用於建立Matcher物件,依照正則表示式,該物件可以與任意字元序列匹配。執行匹配所涉及的所有狀態都駐留在匹配器中,所以多個匹配器可以共享同一模式

分組:簡單的說,分組其實就是為了能夠指定同一個規則可以使用多少次。正則表示式中的分組就是整個大的正則表示式和用()圈起來的內容。

在這個正則表示式“\w(\d\d)(\w+)”中

分組0:是“\w(\d\d)(\w+)”

分組1:是(\d\d)

分組2:是(\w+)

如果我們稍稍變換一下,將原先的正則表示式改為“(\w)(\d\d)(\w+)”,我們的分組就變成了

分組0:是“\w(\d\d)(\w+)”

分組1:是“(\w)”

分組2:是“(\d\d)”

分組3:是“(\w+)”

我們看看和正則表示式”\w(\d\d)(\w+)”匹配的一個字串A22happy

group(0)是匹配整個表示式的字串的那部分A22happy

group(1)是第1組(dd)匹配的部分:22

group(2)是第2組(w+)匹配的那部分happy

public static void main(String[] args) {

String Regex=“\\w(\\d\\d)(\\w+)”;

String TestStr=“A22happy”;

Pattern p=Pattern。compile(Regex);

Matcher matcher=p。matcher(TestStr);

if (matcher。find()) {

int gc=matcher。groupCount();

for (int i = 0; i

System。out。println(“group ”+i+“ :”+matcher。group(i));

}

}

}

start()方法的使用

public static void testStart(){

//建立一個 Matcher ,使用 Matcher。start()方法

String candidateString = “My name is Bond。 James Bond。”;

String matchHelper[] ={“ ^”,“ ^”};

Pattern p = Pattern。compile(“Bond”);

Matcher matcher = p。matcher(candidateString);

//找到第一個 ‘Bond’的開始下標

matcher。find();

int startIndex = matcher。start();

System。out。println(candidateString);

System。out。println(matchHelper[0] + startIndex);

//找到第二個‘Bond’的開始下標

matcher。find();

int nextIndex = matcher。start();

System。out。println(candidateString);

System。out。println(matchHelper[1] + nextIndex);

}

執行結果:

28 正則表示式的應用

/**

* 測試matcher。group方法

*/

public static void testGroup() {

// 建立一個 Pattern

Pattern p = Pattern。compile(“Bond”);

// 建立一個 Matcher ,以便使用 Matcher。group() 方法

String candidateString = “My name is Bond。 James Bond。”;

Matcher matcher = p。matcher(candidateString);

// 提取 group

matcher。find();

System。out。println(String。format(“group匹配的字串 : %s”,matcher。group()));

System。out。println(String。format(“匹配的開始位置 : %d”, matcher。start()));

System。out。println(String。format(“匹配的結束位置 : %d”, matcher。end()));

System。out

。println(“——-再次使用matcher。find()方法,看看matcher中group、start、end方法的效果”);

matcher。find();

System。out。println(String。format(“group匹配的字串 : %s”,matcher。group()));;

System。out。println(String。format(“匹配的開始位置 : %d”, matcher。start()));

System。out。println(String。format(“匹配的結束位置 : %d”, matcher。end()));

System。out。println(String。format(“candidateString字串的長度 : %d”, candidateString。length()));

}

執行結果:

28 正則表示式的應用

獲取由三個字元組成的單詞

package cn。itcast_05;

import java。util。regex。Matcher;

import java。util。regex。Pattern;

/*

* 獲取功能:

* 獲取下面這個字串中由三個字元組成的單詞

* da jia ting wo shuo,jin tian yao xia yu,bu shang wan zi xi,gao xing bu?

*/

public class RegexDemo2 {

public static void main(String[] args) {

// 定義字串

String s = “da jia ting wo shuo,jin tian yao xia yu,bu shang wan zi xi,gao xing bu?”;

// 規則

String regex = “\\b\\w{3}\\b”;

// 把規則編譯成模式物件

Pattern p = Pattern。compile(regex);

// 透過模式物件得到匹配器物件

Matcher m = p。matcher(s);

// 呼叫匹配器物件的功能

// 透過find方法就是查詢有沒有滿足條件的子串

// public boolean find()

// boolean flag = m。find();

// System。out。println(flag);

// // 如何得到值呢?

// // public String group()

// String ss = m。group();

// System。out。println(ss);

//

// // 再來一次

// flag = m。find();

// System。out。println(flag);

// ss = m。group();

// System。out。println(ss);

while (m。find()) {

System。out。println(m。group());

}

// 注意:一定要先find(),然後才能group()

// IllegalStateException: No match found

// String ss = m。group();

// System。out。println(ss);

}

}

判斷身份證:要麼是15位,要麼是18位,最後一位可以為字母,並寫程式提出其中的年月日。

public static void main(String[] args) {

testID_Card();

}

public static void testID_Card() {

// 測試是否為合法的身份證號碼

String[] strs = { “130681198712092019”, “13068119871209201x”,

“13068119871209201”, “123456789012345”, “12345678901234x”,

“1234567890123” };

// 準備正則表示式(身份證有15位和18位兩種,身份證的最後一位可能是字母)

String regex = “(\\d{14}\\w)|\\d{17}\\w”;

// 準備開始匹配,判斷所有的輸入是否是正確的

Pattern regular = Pattern。compile(regex); // 建立匹配的規則Patter

StringBuilder sb = new StringBuilder();

// 遍歷所有要匹配的字串

for (int i = 0; i < strs。length; i++) {

Matcher matcher = regular。matcher(strs[i]);// 建立一個Matcher

sb。append(“身份證: ”);

sb。append(strs[i]);

sb。append(“ 匹配:”);

sb。append(matcher。matches());

System。out。println(sb。toString());

sb。delete(0, sb。length());// 清空StringBuilder的方法

}

GetBirthDay(strs);

}

private static void GetBirthDay(String[] strs) {

System。out。println(“準備開始獲取出生日期”);

// 準備驗證規則

Pattern BirthDayRegular = Pattern。compile(“(\\d{6})(\\d{8})(。*)”);

// 。*連在一起就意味著任意數量的不包含換行的字元

Pattern YearMonthDayRegular = Pattern。compile(“(\\d{4})(\\d{2})(\\d{2})”);

for (int i = 0; i < strs。length; i++) {

Matcher matcher = BirthDayRegular。matcher(strs[i]);

if (matcher。matches()) {

Matcher matcher2 = YearMonthDayRegular。matcher(matcher。group(2));

if (matcher2。matches()) {

System。out。println(strs[i]+“ 中的出生年月分解為: ”+“年” + matcher2。group(1) + “ 月:” + matcher2。group(2) + “ 日:” + matcher2。group(3));

}

}

}

}

執行結果:

28 正則表示式的應用

2。 正則表示式工具類

import java。util。regex。Matcher;

import java。util。regex。Pattern;

/**

* 正則工具類 提供驗證郵箱、手機號、電話號碼、身份證號碼、數字等方法

*/

public final class RegexUtils {

/**

* 驗證Email

*

* @param email

* email地址,格式:zhangsan@sina。com,zhangsan@xxx。com。cn,xxx代表郵件服務商

* @return 驗證成功返回true,驗證失敗返回false ^ :匹配輸入的開始位置。 \:將下一個字元標記為特殊字元或字面值。

* :匹配前一個字元零次或幾次。 + :匹配前一個字元一次或多次。 (pattern) 與模式匹配並記住匹配。 x|y:匹配 x 或

* y。 [a-z] :表示某個範圍內的字元。與指定區間內的任何字元匹配。 \w :與任何單詞字元匹配,包括下劃線。

*

* {n,m} 最少匹配 n 次且最多匹配 m 次 $ :匹配輸入的結尾。

*/

public static boolean checkEmail(String email) {

String regex = “^(\\w)+(\\。\\w+)*@(\\w)+((\\。\\w{2,3}){1,3})$”;

TAG: Stringmatcher匹配systemout