java正则表达式学习笔记(一)

    java正则表达式是从JDK1.4开始才加入的,在JDK1.4以前要解决字符串匹配问题常采用java.util包下的StringTokenizer类,或使用 String 的 split 方法,但这都不是最好的方法,所以JDK1.4开始加入正则表达式,其实其它的语言早就有正则表达式了,如Perl,PHP,javascript等语言,正则表达式也被认为是未来最重要的十大计算机技术之一.
下面我们先看一个例子:

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));
}
}

 


 

上面的例子虽然简单,但也实现了正则表达式,运用了String类的matches()方法实现的,matches()方法的

原型:

 

 

public boolean matches(String regex)
告知此字符串是否匹配给定的正则表达式。
调用此方法的 str.matches(regex) 形式与以下表达式产生的结果完全相同:

Pattern.matches(regex, str)

参数:
regex
- 用来匹配此字符串的正则表达式
返回:
当且仅当此字符串匹配给定的正则表达式时,返回
true
抛出:
PatternSyntaxException
- 如果正则表达式的语法无效

 


 

早上的学习就到这里,下次继续,上面如有误,高手不妨指点!

 

posted @ 2008-10-21 10:52  幽梦新影  阅读(336)  评论(0编辑  收藏  举报