一、初步認識
正則表達式是由一些特定的字符組成,代表一個規(guī)則,可以用來檢驗數(shù)據(jù)格式是否合法,也可以在一段文本中查找滿足要求的內(nèi)容。
如果使用代碼檢驗數(shù)據(jù)是否正確:
public class RegexTest1 {
public static void main(String[] args) {
//需求:檢驗QQ號是否正確,全是數(shù)字不能以0開頭,長度6-20
System.out.println(checkQQ(null));
System.out.println(checkQQ("3563gjhg88"));
System.out.println(checkQQ("764765467"));
}
public static boolean checkQQ(String qq){
//1.判斷qq號碼是否為null
if(qq == null || qq.startsWith("0") || qq.length()<6 || qq.length()>20){
//String提供的一個startWith()方法
return false;
}
//2.判斷qq號碼中全是數(shù)字
// 比如qq號是2894qqi
//遍歷字符
for (int i = 0; i < qq.length(); i++) {
//根據(jù)索引提取當前位置處的字符
char ch = qq.charAt(i);
//需要判斷ch記錄的字符,如果不是數(shù)字,就不合法,底層比較編號
if(ch < '0' || ch > '9'){
return false;
}
}
return true;
}
}
使用正則表達式:
?二、書寫規(guī)則
String提供了一個匹配正則表達式的方法:? 圖片來源heimait
\\d才會當成\d使用
(?i)表示忽略大小寫
三、應用案例
檢驗手機號碼和郵箱是否正確:
import java.util.Scanner;
public class Test2 {
public static void main(String[] args) {
// checkPhone();
checkMail();
}
public static void checkPhone(){
while (true) {
System.out.println("請輸入電話號碼");
Scanner sc = new Scanner(System.in);
String phone = sc.next();
//17728365549 010-8818339 010293737
if(phone.matches("(1[3-9]\\d{9})|(0\\d{2,7}-?[1,9]\\d{4,19})")){
System.out.println("輸入的號碼沒有問題");
break;
}else{
System.out.println("輸入的號碼有問題,請重新輸入號碼");
}
}
}
public static void checkMail(){
while (true) {
System.out.println("請輸入郵箱");
Scanner sc = new Scanner(System.in);
String mail = sc.next();
//1241213254@qq.com 1422341@qq.com hekiii@iaii.com.cn
if(mail.matches("\\w{2,}@\\w{2,20}(\\.\\w{2,10}){1,2}")){
System.out.println("輸入的郵箱沒有問題");
break;
}else{
System.out.println("輸入的郵箱有問題,請重新輸入郵箱");
}
}
}
}
查找信息:
1.定義查找規(guī)則 String regex = " .... "
2.把正則表達式封裝成一個Pattern對象? Pattern pattern = Pattern.compile(regex)
3.通過pattern對象去獲取查找內(nèi)容的匹配器對象? Matcher matcher = pattern.matcher(data)
4.定義一個循環(huán)開始爬取信息文章來源:http://www.zghlxwxcb.cn/news/detail-831171.html
while (matcher.find()){String rs = matcher.group(); rs.sout}文章來源地址http://www.zghlxwxcb.cn/news/detail-831171.html
到了這里,關于正則表達式(Java)的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網(wǎng)!