正则表达 运用 验证qq和邮箱是否符合要求
public class test02 {
public static void main(String[] args) {
String qq="123456789";
String email="12345@qq.com";
checkqq(qq);
checkemail(email);
}
private static void checkemail(String email) {
boolean a=email.matches("\\w+@\\w+(\\.\\w+)+");//xx@xx.com xx@xx.com.cn
System.out.println("该邮箱"+a);
}
private static void checkqq(String qq) {
boolean a=qq.matches("[1-9][0-9]{4,13}");//要求第一位不能为0,最短5位最长14位
System.out.println("该号码"+a);
}
}
结果
该号码true
该邮箱true
学习心得
正则表达式是一个字符串,使用单个字符串来描述、用来定义匹配规则,匹配一系列符合某个句法规则的字符串。在开发中,正则表达式通常被用来检索、替换那些符合某个规则的文本。
常用方法:matches(匹配) split(分割) replaceAll(替换)
校验qq号码.
1: 要求必须是5-15位数字
2: 0不能开头
String qq = "123456789";
String regex = "[1-9][0-9]{4,14}";
boolean flag2 = qq.matches(regex);
分割出字符串中的的数字
代码演示:
public static void main(String[] args) {
String a="19-15-66-44";
String[] b=a.split("-");
for(int c=0;c<b.length;c++) {
System.out.print(b[c]+",");
}
}
结果:19,15,66,44,
代码演示:
public static void main(String[] args) {
String a="18 16 88 52 16";
String[] b=a.split(" ");
for(int c=0;c<b.length;c++) {
System.out.print(b[c]+",");
}
}
结果:18,16,88,52,16,
public static void main(String[] args) {
String a="hello12345world";
String b=a.replaceAll("[0-9]", "*");
System.out.print(b);
}
结果:hello*****world
其他常用含义见链接:
百度百科中的正则表达式