javaRegex學習筆記(一)

來源:互聯網
上載者:User

    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的文法無效

 


 

早上的學習就到這裡,下次繼續,上面如有誤,高手不妨指點!

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.