Java通过Pattern类使用正则表达式

代码示例:

 1 /**
 2  * 判断字符串是否是数字
 3  */
 4 @Test
 5 public void testIsNum(){
 6     String str = "123244你好3";
 7     Pattern pattern = Pattern.compile("[0-9]+$");
 8     boolean matches = pattern.matcher(str).matches();
 9     System.out.println(str + "字符串是否纯数字:" + (matches ? "✔" : "✖"));
10 }
11 
12 /**
13  * 判断字符串是否是指定的手机号码
14  */
15 @Test
16 public void testIsNum2(){
17     String str = "15312345678";
18     Pattern pattern = Pattern.compile("([1][3][5]|[1][5][3])[0-9]{8}");
19     boolean matches = pattern.matcher(str).matches();
20     System.out.println(str + "电话号码是否合法:" + (matches ? "✔" : "✖"));
21 }