验证邮箱的正则表达式代码如下:
package matches;
public class Match1 {
public static void main(String[] args) {
String regex = "(\\w{3,10}\\.)*\\w+@\\w+(\\.\\w{2,3})*\\.\\w{2,3}";
String str1 = "test@zzz.com";
String str2 = "test@@.com";
String str3 = "xdq.hhh@gmail.com";
if (str1.matches(regex))
System.out.println(str1 + "是一个合法的Email地址");
if (str2.matches(regex))
System.out.println(str2 +"是一个合法的Email地址");
if (str3.matches(regex))
System.out.println(str3 +"是一个合法的Email地址");
/*
* 输出
* test@zzz.com是一个合法的Email地址
* xdq.hhh@gmail.com是一个合法的Email地址
*/
}
}
博主在写邮箱验证的时候才发现String有matches这个方法,蛮方便的。不过需要注意的是,String的matches方法和用Matcher的find方法的区别,博主在第一次的时候也中招的了。
使用Matcher的find方法,只要String中含有Regex的模式,就匹配成功。
package matches;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Match2 {
public static void main(String[] args) {
String regex = "233";
String str1 = "-.- 2333";
String str2 = "a333323";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(str1);
if (matcher.find())
System.out.println(str1 + "匹配成功");
matcher = pattern.matcher(str2);
if (matcher.find())
System.out.println(str2 + "匹配成功");
/* 输出
* -.- 2333匹配成功
*/
}
}
使用String的matches方法,则是要整个字符串与Regex的模式完全匹配才可以。
package matches;
public class Match3 {
public static void main(String[] args) {
String regex = "233";
String str1 = "-.- 2333";
String str2 = "a333323";
String str3 = "233";
if (str1.matches(regex))
System.out.println(str1 + "匹配成功");
if (str2.matches(regex))
System.out.println(str2 + "匹配成功");
if (str3.matches(regex))
System.out.println(str3 + "匹配成功");
/*
* 输出
* 233匹配成功
*/
}
}
附上关于String的matches方法的文档介绍
boolean java.lang.String.matches(String regex)
matches
public boolean matches(String regex)Tells whether or not this string matches the given regular expression.
An invocation of this method of the form str.matches(regex) yields exactly the same result as the expressionPattern.matches(regex, str)
Parameters:regex - the regular expression to which this string is to be matchedReturns:true if, and only if, this string matches the given regular expressionThrows:PatternSyntaxException - if the regular expression’s syntax is invalidSince:1.4See Also:Pattern
从文档中可以看到,matches方法和Pattern.matches(regex, str)方法是一样的,也就是说博主在此之前不知道Pattern.matches这个方法。