一 应用正则表达式
1 代码
public class RegExp{ public static void main(String[] args) throws Exception { if ("123".matches("\\d+")) { System.out.println("由数字组成!"); } else { System.out.println("不是由数字组成!"); } }}
2 运行
由数字组成!
二 字符串替换——过滤字符串中的数字
1 代码
public class SubString{ public static void main(String[] args) throws Exception { String str = "a1b22c333d4444e55555f6666666g"; String regex = "[0-9]+"; // 数字出现1次或多次 //String regex = "\\d+"; // 数字出现1次或多次 System.out.println(str.replaceAll(regex, "")); }}
2 运行
abcdefg
三 正则验证邮箱格式
1 代码
import java.util.*;public class EmailValidation{ public static void main(String[] args) throws Exception { String str = null; String regex = "\\w+@\\w+.\\w+"; Scanner reader = new Scanner(System.in); do { System.out.print("请输入一个有效的邮件地址:"); str = reader.next(); System.out.println(str); } while (!str.matches(regex)); System.out.println("邮件地址有效!谢谢注册!"); reader.close(); }}
2 运行
请输入一个有效的邮件地址:4月好4月好请输入一个有效的邮件地址:yy@qq.comyy@qq.com邮件地址有效!谢谢注册!