1、什么是正則表達式?
正則表達式(regular expression)是根據字符串集合內每個字符串共享的共同特性來描述字符串集合的一種途徑。正則表達式可以用於搜索、編輯或者處理文本和數據。
Java.util.regex主要包含以下三類:
- pattern類:
pattern 對象是一個正則表達式的編譯表示。Pattern 類沒有公共構造方法。要創建一個 Pattern 對象,你必須首先調用其公共靜態編譯方法,它返回一個 Pattern 對象。該方法接受一個正則表達式作為它的第一個參數。 - Matcher類:
Matcher 對象是對輸入字符串進行解釋和匹配操作的引擎。與Pattern 類一樣,Matcher 也沒有公共構造方法。你需要調用 Pattern 對象的 matcher 方法來獲得一個 Matcher 對象。 - PatternSyntaxException:
PatternSyntaxException 是一個非強制異常類,它表示一個正則表達式模式中的語法錯誤。
2、正則表達式主要用於對password、phone、Email等的合法性檢查以下就是其簡單應用:
對應的類:
package cn.lovepi.chapter07.action;
import com.opensymphony.xwork2.ActionSupport;
import java.util.regex.Pattern;
/**
*
* 數據校驗示例——硬編碼格式
*/
public class ValidateAction extends ActionSupport{
private String username;
private String password;
private String repassword;
private String email;
private String phonenumber;
private int age;
@Override
public String execute() throws Exception {
return SUCCESS;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getRepassword() {
return repassword;
}
public void setRepassword(String repassword) {
this.repassword = repassword;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPhonenumber() {
return phonenumber;
}
public void setPhonenumber(String phonenumber) {
this.phonenumber = phonenumber;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
類對應的校驗方法:
public void validateExecute(){
if (null==username || username.length()<6 ||username.length()>10) {
this.addFieldError("username", "username has error");
}
if (null==password || password.length()<6||password.length()>10) {
this.addFieldError("password", "password has error");
}else if (null==repassword || repassword.length()<6||repassword.length()>10) {
this.addFieldError("repassword", "repassword has error");
}else if(!password.equals(repassword)){
this.addFieldError("password", "tow password is not be same");
}
if (age<=0 ||age>150) {
this.addFieldError("age", "年齡不符合人類規范!");
}
//驗證郵箱! 123dsaw@163.com
//只允許a-z A-Z 1-9 -_
//正則表達式---專門用於復雜字符判斷的技術
Pattern p = Pattern.compile("^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\\.([a-zA-Z0-9_-])+)+$");
if (null==email || !p.matcher(email).matches()) {
this.addFieldError("email", "郵箱驗證失敗!");
}
Pattern p1=Pattern.compile("^(((13[0-9])|(15([0-3]|[5-9]))|(18[0,5-9]))\\d{8})|(0\\d{2}-\\d{7,8})|(0\\d{3}-\\d{7,8})$");
if (null==phonenumber || !p1.matcher(phonenumber).matches()) {
this.addFieldError("phonenumber", "電話格式不正確!");
this.addActionError("action級別錯誤!");
}
}
參考鏈接:
https://blog.csdn.net/icarus_wang/article/details/53997632?locationNum=9&fps=1