javaRegex是從JDK1.4開始才加入的,在JDK1.4以前要解決字串匹配問題常採用java.util包下的StringTokenizer類,或使用 String 的 split 方法,但這都不是最好的方法,所以JDK1.4開始加入Regex,其實其它的語言早就有Regex了,如Perl,PHP,javascript等語言,Regex也被認為是未來最重要的十大電腦技術之一.
下面我們先看一個例子:
public class RegEx{
public static void main(String[] args) {
String regEx1 = "^[a-zA-Z0-9]{5,12}$";//5-12位使用者名稱只能是字母或者是數字
String regEx2 = "^[a-zA-Z0-9]{6,16}$";//6-16位使用者密碼只能是字母或者是數字
String regEx3 = "^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+[.]((net)|(com))$";//郵箱驗證,email有@有.
String user = "lovefeel2004";
if(user.matches(regEx1)){//匹配正則,實現使用者輸入驗證
System.out.println("ok");
}else{
System.out.println("usrsname id error");
}
String password ="123abc456ABC";
System.out.println(password.matches(regEx2));
String email ="lovefeel2004@126.com";
System.out.println(email.matches(regEx3));
}
}
上面的例子雖然簡單,但也實現了Regex,運用了String類的matches()方法實現的,matches()方法的
原型:
public boolean matches(String regex)
告知此字串是否匹配給定的Regex。
調用此方法的 str.matches(regex) 形式與以下運算式產生的結果完全相同:
Pattern.matches(regex, str)
參數:
regex - 用來匹配此字串的Regex
返回:
若且唯若此字串匹配給定的Regex時,返回 true
拋出:
PatternSyntaxException - 如果Regex的文法無效
早上的學習就到這裡,下次繼續,上面如有誤,高手不妨指點!