The following code uses regular expressions to verify the input formats including verification of email and verification of mobile phone numbers.
The code copy is as follows:
package com.firewolf.utils;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Verify input format using regular expressions
* @author liuxing
*
*/
public class RegexValidateUtil {
public static void main(String[] args) {
System.out.println(checkEmail("[email protected]"));
System.out.println(checkMobileNumber("071-3534452"));
}
/**
* Verify email
* @param email
* @return
*/
public static boolean checkEmail(String email){
boolean flag = false;
try{
String check = "^([a-z0-9A-Z]+[-|_|//.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+( -[a-z0-9A-Z]+)?//.)+[a-zA-Z]{2,}$";
Pattern regex = Pattern.compile(check);
Matcher matcher = regex.matcher(email);
flag = matcher.matches();
}catch(Exception e){
flag = false;
}
return flag;
}
/**
* Verify mobile phone number
* @param mobiles
* @return
*/
public static boolean checkMobileNumber(String mobileNumber){
boolean flag = false;
try{
Pattern regex = Pattern.compile("^(((13[0-9])|(15([0-3]|[5-9]))|(18[0,5-9]))// d{8})|(0//d{2}-//d{8})|(0//d{3}-//d{7})$");
Matcher matcher = regex.matcher(mobileNumber);
flag = matcher.matches();
}catch(Exception e){
flag = false;
}
return flag;
}
}
PS: Here are two very convenient regular expression tools for your reference:
JavaScript regular expression online testing tool:
http://tools.VeVB.COM/regex/javascript
Regular expression online generation tool:
http://tools.VeVB.COM/regex/create_reg