欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Java正则表达式验证IP,邮箱,电话

程序员文章站 2023-10-18 22:38:27
引言 java中我们会常用一些判断如IP、电子邮箱、电话号码的是不是合法,那么我们怎么来判断呢,答案就是利用正则表达式来判断了,废话不多说,下面就是上代码。 1:判断是否是正确的IP 2:判断是否是正确的邮箱地址 3:判断是否是手机号码 ......

 引言

    java中我们会常用一些判断如ip、电子邮箱、电话号码的是不是合法,那么我们怎么来判断呢,答案就是利用正则表达式来判断了,废话不多说,下面就是上代码。

1:判断是否是正确的ip 

 1         /**
 2          * 用正则表达式进行判断
 3          */
 4         public boolean isipaddressbyregex(string str) {
 5             string regex = "\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}";
 6             // 判断ip地址是否与正则表达式匹配
 7             if (str.matches(regex)) {
 8                 string[] arr = str.split("\\.");
 9                 for (int i = 0; i < 4; i++) {
10                     int temp = integer.parseint(arr[i]);
11                     //如果某个数字不是0到255之间的数 就返回false
12                     if (temp < 0 || temp > 255) return false;
13                 }
14                 return true;
15             } else return false;
16         }

 

2:判断是否是正确的邮箱地址  

1 /**
2 *正则表达式验证邮箱
3 */
4  public static boolean isemail(string email) {
5        if (email == null || "".equals(email)) return false;
6             string regex = "\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*";
7            return email.matches(regex);
8   }

 

3:判断是否是手机号码

1  /**
2 *正则表达式验证手机
3 */
4 public static boolean orphonenumber(string phonenumber) {
5        if (phonenumber == null || "".equals(phonenumber))
6             return false;
7            string regex = "^1[3|4|5|8][0-9]\\d{8}$";
8            return phonenumber.matches(regex);
9     }