29 System.out.println(match);
30 //获取该group的起始下标
31 int start = matcher.start();
32 //获取该group的结束下标
33 int end = matcher.end();
34 System.out.println(start);
35 System.out.println(end);
36 }
37 public static void main(String[] args) {
38 testNormalSearch();
39 testSearchAndReplace();
40 testSearchAndReplace();
41 }
42 }
43 /* 输出结果如下:
44 true
45 b
46 2
47 3
48 x b c x b c
49 I love Java. Ice is my favorite. Ice Ice Ice.
50 */
复制代码
5) 用正则表达式验证电子邮件地址是否合法:
1 public static void main(String args[]) {
2 String EMAIL_REGEX = "^[\\w-_\\.+]*[\\w-_\\.]\\@([\\w]+\\.)+[\\w]+[\\w]$";
3 String email = "user@domain.com";
4 if (email.matches(EMAIL_REGEX)) {
5 System.out.println("This is a valid email.");
6 }
7 }
8 /* 输出结果如下:
9 This is a valid email.
10 */
复制代码
6) 判断日期的合法性:
1 public static void main(String args[]) {
2 String date = "12/12/1212";
3 String datePattern = "\\d{1,2}/\\d{1,2}/\\d{4}";
4 System.out.println(date.matches(datePattern));
5 }
6 /* 输出结果如下: www.2cto.com
7 true
8 */
复制代码
7) 国内带区号的电话号码匹配:
1 public static void main(String args[]) {
2 String phoneNumber = "(010)1234567";
3 //由于(和)都是正则中的meta字符,因此需要在其前面加\,以表示其原始含义。
4 String pattern = "^(\\(0[0-9]{2,3}\\)) [0-9]{7,8}$";
5 System.out.println(phoneNumber.matches(pattern));
6 }
7 /* 输出结果如下:
8 true
9 */
复制代码
8) 验证IPv4地址的合法性:
1 public class MyTest {
2 public static boolean checkIPV4(String ipAddress) {
3 String regex0 = "(2[0-4]\\d)" + "|(25[0-5])";
4 String regex1 = "1\\d{2}";
5 String regex2 = "[1-9]\\d";
6 String regex3 = "\\d";
7 StringBuilder builder = new StringBuilder(256);
8 builder.append("(").append(regex0).append(")|(").append(regex1)
9 .append(")|(").append(regex2).append(")|(").append(regex3)
10 .append(")");
11 StringBuilder builder2 = new StringBuilder(1024);
12 builder2.append("(").append(builder).append(").(").append(builder)
13 .append(").(").append(builder).append(").(").append(builder)
14 .append(")");
15 Pattern p = Pattern.compile(builder2.toString());
16 Matcher m = p.matcher(ipAddress);
17 return m.matches();
18 }
19
20 public static void main(String args[]) {
21 System.out.println("192.168.0.1 is "
22 + (checkIPV4("192.168.0.1") "legal IP" : "illegal IP"));
23 }
24 }
25 /* 输出结果如下:
26 192.168.0.1 is legal IP
27 */