正则表达式
-
概述:
正则表达式就是正确规则的表达式,是一种特殊的语法,事先将一些特定的字符或字符串组合在一起来表示过滤逻辑的字符串。 -
作用:
一般用于校验字符串 -
常见正则表达式:
String regex;
regx = “a”;
regx = “[a,b,c]”; //只要是a,b,c中的任意一个就可以
regx = “[1,2,3,4,5,6,7,8,9]”;
regx = “[^0-9]”; //不是我0-9中的某一个
regx = “[A-Za-z0-9]”;//表示A-Z,a-z,0-9均可
regx = “.”;//通配符,统配任意单个字符
regx = “\.”; //只匹配‘ . ’本身,需要用转意符 \
regx = “…”; //匹配两个任意字符
regx = “\|”; // | 或者
regx="\d"; // 等同于[0-9]
regx="\w"; //等同于[0-9a-z_A-Z]
regx=“a*”; //0次或多次
regx="[a-z]?"; // ? 0次或一次
regx="[a-zA-Z0-9]+"; //+ 一次或多次
regx="[a-z]{5}"; //正好n次
regx="[a-z]{2,}"; //不能少于2次
regx="[0-9]{5,9}"; //大于等于5 小于等于 9
PS:
“abc”.matches(regx); 用来判断你这个字符串,是否符合这个正则表达式 -
例:
判断邮箱的正则表达
public class Test {
public static void main(String[] args) {
// 邮箱的正则 6~18个字符,可使用字母、数字、下划线,需以字母开头
String regex;
regex="[a-zA-Z]\\w{5,17}@[a-z1-9]{2,10}\\.(com|net|cn|org)}";
String str="lqz1373712225@163.com";
boolean matches = str.matches(regex);
if(matches){
System.out.println("输入符合规范");
}else{
System.out.println("输入不符合规范");
}
}
}
手机号码的正则表达式:
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
//手机号的规则 11位 以 1开头 每一位都是数字 13 15 17 18
String Regex="[1][3,5,7,8][0-9]{9}";
System.out.println("请输入电话号码");
Scanner sc = new Scanner(System.in);
String phnum = sc.nextLine();
if(phnum.matches(Regex)){
System.out.println("手机号输入正确");
}else{
System.out.println("手机号输入错误");
}
}
}