接下來(lái),學(xué)習(xí)一個(gè)全新的知識(shí),叫做正則表達(dá)式。正則表達(dá)式其實(shí)是由一些特殊的符號(hào)組成的,它代表的是某種規(guī)則。
正則表達(dá)式的作用1:用來(lái)校驗(yàn)字符串?dāng)?shù)據(jù)是否合法
正則表達(dá)式的作用2:可以從一段文本中查找滿足要求的內(nèi)容
5.1 正則表達(dá)式初體驗(yàn)
現(xiàn)在,我們就以QQ號(hào)碼為例,來(lái)體驗(yàn)一下正則表達(dá)式的用法。注意:現(xiàn)在僅僅只是體驗(yàn)而已,我們還沒(méi)有講正則表達(dá)式的具體寫(xiě)法。
- 不使用正則表達(dá)式,校驗(yàn)QQ號(hào)碼代碼是這樣的
public static boolean checkQQ(String qq){
// 1、判斷qq號(hào)碼是否為null
if(qq == null || qq.startsWith("0") || qq.length() < 6 || qq.length() > 20){
return false;
}
// 2、qq至少是不是null,不是以0開(kāi)頭的,滿足6-20之間的長(zhǎng)度。
// 判斷qq號(hào)碼中是否都是數(shù)字。
// qq = 2514ghd234
for (int i = 0; i < qq.length(); i++) {
// 根據(jù)索引提取當(dāng)前位置處的字符。
char ch = qq.charAt(i);
// 判斷ch記住的字符,如果不是數(shù)字,qq號(hào)碼不合法。
if(ch < '0' || ch > '9'){
return false;
}
}
// 3、說(shuō)明qq號(hào)碼肯定是合法
return true;
}
- 用正則表達(dá)式代碼是這樣的
public static boolean checkQQ1(String qq){
return qq != null && qq.matches("[1-9]\\d{5,19}");
}
我們發(fā)現(xiàn),使用正則表達(dá)式,大大簡(jiǎn)化的了代碼的寫(xiě)法。這個(gè)代碼現(xiàn)在不用寫(xiě),體驗(yàn)到正則表達(dá)式的優(yōu)勢(shì)就可以了。
5.2 正則表達(dá)式書(shū)寫(xiě)規(guī)則
前面我們已經(jīng)體驗(yàn)到了正則表達(dá)式,可以簡(jiǎn)化校驗(yàn)數(shù)據(jù)的代碼書(shū)寫(xiě)。這里需要用到一個(gè)方法叫matches(String regex)
。這個(gè)方法時(shí)屬于String類(lèi)的方法。
這個(gè)方法是用來(lái)匹配一個(gè)字符串是否匹配正則表達(dá)式的規(guī)則,參數(shù)需要調(diào)用者傳遞一個(gè)正則表達(dá)式。但是正則表達(dá)式不能亂寫(xiě),是有特定的規(guī)則的。
下面我們就學(xué)習(xí)一下,正則表達(dá)式的規(guī)則。從哪里學(xué)呢?在API中有一個(gè)類(lèi)叫做Pattern,我們可以到API文檔中搜索,關(guān)于正則表達(dá)式的規(guī)則,這個(gè)類(lèi)都告訴我們了。我這里把常用的已經(jīng)給大家整理好了。
我們將這些規(guī)則,在代碼中演示一下
/**
* 目標(biāo):掌握正則表達(dá)式的書(shū)寫(xiě)規(guī)則
*/
public class RegexTest2 {
public static void main(String[] args) {
// 1、字符類(lèi)(只能匹配單個(gè)字符)
System.out.println("a".matches("[abc]")); // [abc]只能匹配a、b、c
System.out.println("e".matches("[abcd]")); // false
System.out.println("d".matches("[^abc]")); // [^abc] 不能是abc
System.out.println("a".matches("[^abc]")); // false
System.out.println("b".matches("[a-zA-Z]")); // [a-zA-Z] 只能是a-z A-Z的字符
System.out.println("2".matches("[a-zA-Z]")); // false
System.out.println("k".matches("[a-z&&[^bc]]")); // : a到z,除了b和c
System.out.println("b".matches("[a-z&&[^bc]]")); // false
System.out.println("ab".matches("[a-zA-Z0-9]")); // false 注意:以上帶 [內(nèi)容] 的規(guī)則都只能用于匹配單個(gè)字符
// 2、預(yù)定義字符(只能匹配單個(gè)字符) . \d \D \s \S \w \W
System.out.println("徐".matches(".")); // .可以匹配任意字符
System.out.println("徐徐".matches(".")); // false
// \轉(zhuǎn)義
System.out.println("\"");
// \n \t
System.out.println("3".matches("\\d")); // \d: 0-9
System.out.println("a".matches("\\d")); //false
System.out.println(" ".matches("\\s")); // \s: 代表一個(gè)空白字符
System.out.println("a".matches("\s")); // false
System.out.println("a".matches("\\S")); // \S: 代表一個(gè)非空白字符
System.out.println(" ".matches("\\S")); // false
System.out.println("a".matches("\\w")); // \w: [a-zA-Z_0-9]
System.out.println("_".matches("\\w")); // true
System.out.println("徐".matches("\\w")); // false
System.out.println("徐".matches("\\W")); // [^\w]不能是a-zA-Z_0-9
System.out.println("a".matches("\\W")); // false
System.out.println("23232".matches("\\d")); // false 注意:以上預(yù)定義字符都只能匹配單個(gè)字符。
// 3、數(shù)量詞: ? * + {n} {n, } {n, m}
System.out.println("a".matches("\\w?")); // ? 代表0次或1次
System.out.println("".matches("\\w?")); // true
System.out.println("abc".matches("\\w?")); // false
System.out.println("abc12".matches("\\w*")); // * 代表0次或多次
System.out.println("".matches("\\w*")); // true
System.out.println("abc12張".matches("\\w*")); // false
System.out.println("abc12".matches("\\w+")); // + 代表1次或多次
System.out.println("".matches("\\w+")); // false
System.out.println("abc12張".matches("\\w+")); // false
System.out.println("a3c".matches("\\w{3}")); // {3} 代表要正好是n次
System.out.println("abcd".matches("\\w{3}")); // false
System.out.println("abcd".matches("\\w{3,}")); // {3,} 代表是>=3次
System.out.println("ab".matches("\\w{3,}")); // false
System.out.println("abcde徐".matches("\\w{3,}")); // false
System.out.println("abc232d".matches("\\w{3,9}")); // {3, 9} 代表是 大于等于3次,小于等于9次
// 4、其他幾個(gè)常用的符號(hào):(?i)忽略大小寫(xiě) 、 或:| 、 分組:()
System.out.println("abc".matches("(?i)abc")); // true
System.out.println("ABC".matches("(?i)abc")); // true
System.out.println("aBc".matches("a((?i)b)c")); // true
System.out.println("ABc".matches("a((?i)b)c")); // false
// 需求1:要求要么是3個(gè)小寫(xiě)字母,要么是3個(gè)數(shù)字。
System.out.println("abc".matches("[a-z]{3}|\\d{3}")); // true
System.out.println("ABC".matches("[a-z]{3}|\\d{3}")); // false
System.out.println("123".matches("[a-z]{3}|\\d{3}")); // true
System.out.println("A12".matches("[a-z]{3}|\\d{3}")); // false
// 需求2:必須是”我愛(ài)“開(kāi)頭,中間可以是至少一個(gè)”編程“,最后至少是1個(gè)”666“
System.out.println("我愛(ài)編程編程666666".matches("我愛(ài)(編程)+(666)+"));
System.out.println("我愛(ài)編程編程66666".matches("我愛(ài)(編程)+(666)+"));
}
}
5.3 正則表達(dá)式應(yīng)用案例
學(xué)習(xí)完正則表達(dá)式的規(guī)則之后,接下來(lái)我們?cè)倮谜齽t表達(dá)式,去校驗(yàn)幾個(gè)實(shí)際案例。
-
正則表達(dá)式校驗(yàn)手機(jī)號(hào)碼
/**
* 目標(biāo):校驗(yàn)用戶輸入的電話、郵箱、時(shí)間是否合法。
*/
public class RegexTest3 {
public static void main(String[] args) {
checkPhone();
}
public static void checkPhone(){
while (true) {
System.out.println("請(qǐng)您輸入您的電話號(hào)碼(手機(jī)|座機(jī)): ");
Scanner sc = new Scanner(System.in);
String phone = sc.nextLine();
// 18676769999 010-3424242424 0104644535
if(phone.matches("(1[3-9]\\d{9})|(0\\d{2,7}-?[1-9]\\d{4,19})")){
System.out.println("您輸入的號(hào)碼格式正確~~~");
break;
}else {
System.out.println("您輸入的號(hào)碼格式不正確~~~");
}
}
}
}
- 使用正則表達(dá)式校驗(yàn)郵箱是否正確
public class RegexTest3 {
public static void main(String[] args) {
checkEmail();
}
public static void checkEmail(){
while (true) {
System.out.println("請(qǐng)您輸入您的郵箱: ");
Scanner sc = new Scanner(System.in);
String email = sc.nextLine();
/**
* dlei0009@163.com
* 25143242@qq.com
* itheima@itcast.com.cn
*/
if(email.matches("\\w{2,}@\\w{2,20}(\\.\\w{2,10}){1,2}")){
System.out.println("您輸入的郵箱格式正確~~~");
break;
}else {
System.out.println("您輸入的郵箱格式不正確~~~");
}
}
}
}
5.4 正則表達(dá)式信息爬取
各位小伙伴,在前面的課程中,我們學(xué)習(xí)了正則表達(dá)式的作用之一,用來(lái)校驗(yàn)數(shù)據(jù)格式的正確性。接下來(lái)我們學(xué)習(xí)正則表達(dá)式的第二個(gè)作用:在一段文本中查找滿足要求的內(nèi)容
我們還是通過(guò)一個(gè)案例給大家做演示:案例需求如下
/**
* 目標(biāo):掌握使用正則表達(dá)式查找內(nèi)容。
*/
public class RegexTest4 {
public static void main(String[] args) {
method1();
}
// 需求1:從以下內(nèi)容中爬取出,手機(jī),郵箱,座機(jī)、400電話等信息。
public static void method1(){
String data = " 來(lái)黑馬程序員學(xué)習(xí)Java,\n" +
" 電話:1866668888,18699997777\n" +
" 或者聯(lián)系郵箱:boniu@itcast.cn,\n" +
" 座機(jī)電話:01036517895,010-98951256\n" +
" 郵箱:bozai@itcast.cn,\n" +
" 郵箱:dlei0009@163.com,\n" +
" 熱線電話:400-618-9090 ,400-618-4000,4006184000,4006189090";
// 1、定義爬取規(guī)則
String regex = "(1[3-9]\\d{9})|(0\\d{2,7}-?[1-9]\\d{4,19})|(\\w{2,}@\\w{2,20}(\\.\\w{2,10}){1,2})"
+ "|(400-?\\d{3,7}-?\\d{3,7})";
// 2、把正則表達(dá)式封裝成一個(gè)Pattern對(duì)象
Pattern pattern = Pattern.compile(regex);
// 3、通過(guò)pattern對(duì)象去獲取查找內(nèi)容的匹配器對(duì)象。
Matcher matcher = pattern.matcher(data);
// 4、定義一個(gè)循環(huán)開(kāi)始爬取信息
while (matcher.find()){
String rs = matcher.group(); // 獲取到了找到的內(nèi)容了。
System.out.println(rs);
}
}
}
5.5 正則表達(dá)式搜索、替換
接下來(lái),我們學(xué)習(xí)一下正則表達(dá)式的另外兩個(gè)功能,替換、分割的功能。需要注意的是這幾個(gè)功能需要用到Stirng類(lèi)中的方法。這兩個(gè)方法其實(shí)我們之前學(xué)過(guò),只是當(dāng)時(shí)沒(méi)有學(xué)正則表達(dá)式而已。文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-808117.html
/**文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-808117.html
- 目標(biāo):掌握使用正則表達(dá)式做搜索替換,內(nèi)容分割。
*/
public class RegexTest5 {
public static void main(String[] args) {
// 1、public String replaceAll(String regex , String newStr):按照正則表達(dá)式匹配的內(nèi)容進(jìn)行替換
// 需求1:請(qǐng)把下面字符串中的不是漢字的部分替換為 “-”
String s1 = "古力娜扎ai8888迪麗熱巴999aa5566馬爾扎哈fbbfsfs42425卡爾扎巴";
System.out.println(s1.replaceAll("\\w+", "-"));
// 需求2(拓展):某語(yǔ)音系統(tǒng),收到一個(gè)口吃的人說(shuō)的“我我我喜歡編編編編編編編編編編編編程程程!”,需要優(yōu)化成“我喜歡編程!”。
String s2 = "我我我喜歡編編編編編編編編編編編編程程程";
System.out.println(s2.replaceAll("(.)\\1+", "$1"));
// 2、public String[] split(String regex):按照正則表達(dá)式匹配的內(nèi)容進(jìn)行分割字符串,反回一個(gè)字符串?dāng)?shù)組。
// 需求1:請(qǐng)把下面字符串中的人名取出來(lái),使用切割來(lái)做
String s3 = "古力娜扎ai8888迪麗熱巴999aa5566馬爾扎哈fbbfsfs42425卡爾扎巴";
String[] names = s3.split("\\w+");
System.out.println(Arrays.toString(names));
}
}
到了這里,關(guān)于JAVA中正則表達(dá)式的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!