41 lines
1.5 KiB
Java
41 lines
1.5 KiB
Java
package com.inmind.regex04;
|
||
|
||
import java.util.Arrays;
|
||
|
||
/*
|
||
1. Regex:正则表达式是用字符串写成的一种规则
|
||
|
||
2. String类的方法matches匹配规则
|
||
1. 案例:检查QQ号码是否合法,规则: 必须全数字,不能0开头,最低5位,最高12位
|
||
2. 案例:检查手机号码是否合法,规则:必须1开头,第二位: 34578,全数字,总共11位
|
||
3. String类的方法split
|
||
1. 案例:切割字符串,返回数组
|
||
2. 案例:切割网络ip
|
||
*/
|
||
public class Demo16 {
|
||
public static void main(String[] args) {
|
||
//1. 案例:切割字符串,返回数组
|
||
String str = "刘备,,关羽,,,张飞";
|
||
String[] strings = str.split(",+");
|
||
System.out.println(strings.length);
|
||
System.out.println(Arrays.toString(strings));
|
||
|
||
//2. 案例:切割网络ip
|
||
String ip = "192.168.1.1";
|
||
String[] ips = ip.split("\\.");//表示普通的点号
|
||
System.out.println(ips.length);
|
||
System.out.println(Arrays.toString(ips));
|
||
|
||
}
|
||
|
||
public static void matchTest(String[] args) {
|
||
//1. 案例:检查QQ号码是否合法,规则: 必须全数字,不能0开头,最低5位,最高12位
|
||
String qq = "12345678";
|
||
boolean matches = qq.matches("[1-9]{1}[0-9]{4,11}");
|
||
System.out.println(matches);
|
||
//2. 案例:检查手机号码是否合法,规则:必须1开头,第二位: 34578,全数字,总共11位
|
||
String tel = "13770858888";
|
||
System.out.println(tel.matches("[1]{1}[34578]{1}[0-9]{9}"));
|
||
}
|
||
}
|